Garoon ポータルで OneDrive で管理しているファイル一覧を表示&ファイルを追加しよう

目次

caution
警告

はじめに

この記事では、Garoon のポータル機能を利用して、次のことができる Garoon カスタマイズポートレットを紹介します。

  • OneDrive 内のファイルの一覧を表示する。
  • ポートレットからドラッグ&ドロップで OneDrive へファイル追加する。

必要なもの

  • クラウド版 Garoon
  • Microsoft アカウント

注意事項

  • 使用している Web ブラウザーの設定によっては、サードパーティー Cookie の読み取りを許可する必要があります。

完成イメージ

  • Garoon のポータルに、OneDrive 内のファイル一覧をリスト形式またはサムネイル形式で表示します。
    • リスト形式

    • サムネイル形式

      • リスト形式またはサムネイル形式で、ファイル一覧を表示します。
      • フォルダー名をクリックすると、別タブでそのフォルダーの内容を表示します(OneDrive の画面に移ります)
      • ファイル名をクリックすると、そのファイルをダウンロードできます。
        ポータルを表示して 1 時間以上経過している場合は、ダウンロード URL の有効期限が切れるためファイルをダウンロードできません。ポータル画面を再読み込みすることで、ダウンロードできます。
  • Garoon のポータルから、ドラッグ&ドロップ、または[ファイルを追加]ボタンのクリックで、OneDrive へファイルを追加します。
    • 同名のファイルがある場合は、上書きするかダイアログで選択できます。

システム構成

  1. Garoon から OAuth を用いて Entra ID V2 Endpoint へサインインします。
    Microsoft Authentication Library for JavaScript (MSAL.js) (External link) を利用することで、OAuth を使った認可フローを実現します。
  2. Azure からアクセストークンを取得します。
    このアクセストークンを使って、Microsoft Graph API を実行し、OneDrive のファイルを取得したり更新したりします。
    Microsoft Graph API(以降、Graph API)は、Microsoft 365 サービスの情報を利用する API です。

ファイル一覧を表示するフロー

  1. アクセストークンを使って、OneDrive のファイル情報を取得する API を実行します。
  2. OneDrive のファイル情報が返却されます。
  3. HTML ポートレットにファイル情報(ファイル一覧)を表示します。

ファイルを追加するフロー

  1. アクセストークンを使って、OneDrive にファイルを追加する API を実行します。
  2. ファイル追加後の OneDrive のファイル情報が返却されます。
  3. HTML ポートレットにファイル情報(ファイル一覧)を表示します。

Microsoft Entra ID の設定

Garoon から Graph API (External link) を利用するため、Microsoft Entra ID にアプリケーションを登録します。この設定は、管理者のみ行う作業です。利用者が個々に設定する必要はありません。

アプリケーションの作成

Azure ポータル (External link) で、Microsoft Entra ID にアプリケーションを登録します。
手順は次のページを参照してください。
Garoon ポータルで Outlook の未読メール数をチェックしよう:アプリケーションの作成

  • この記事では、作成するアプリケーション名を「garoon-onedrive」としています。

  • アプリケーション作成後、作成したアプリケーションの詳細画面が表示されます。
    「Application(client)ID」(「アプリケーション(クライアント)ID」)の値をメモしておいてください。
    Garoon カスタマイズファイルで利用します。

    Azure ポータルで[Microsoft Entra ID]をクリックし[App registrations]をクリックしても、詳細画面を開くことができます。

アプリケーションの設定

作成したアプリケーションに対し、次のことを行います。

  1. リダイレクト URL の設定
  2. OAuth 認証スコープの設定
手順1. リダイレクト URL の設定

「リダイレクト URL」と「暗黙の付与」設定を実施します。
手順は次のページを参照してください。
Garoon ポータルで Outlook の未読メール数をチェックしよう - アプリケーションの設定(手順1. リダイレクト URI の設定)

手順2. OAuth 認証スコープの設定

OAuth 認証スコープを設定します。
手順は次の記事を参照してください。
Garoon ポータルで Outlook の未読メール数をチェックしよう - アプリケーションの設定(手順2. OAuth 認証スコープの設定)

設定する Microsoft Graph API のアクセス権は、以下の 2 つです。

  • Files.ReadWrite.All
  • User.Read(デフォルトで設定されている権限)

Garoon の設定

Garoon では、次のことを行います。

  1. Graph API を利用するためのプロキシ API を設定
  2. ポートレットに表示する画像ファイルの、画像アセットへの追加
  3. HTML ポートレットの作成・カスタマイズの適用
  4. ポータルへの配置

なお、このカスタマイズでは、次の外部ライブラリを利用しています。

  • Microsoft Authentication Library for JavaScript(MSAL)v0.1.2, ドキュメント (External link)
  • jQuery v3.3.1, ドキュメント (External link)
    • https://js.cybozu.com/jquery/3.3.1/jquery.min.js
  • SweetAlert2 v8.2.1, ドキュメント (External link)
    • https://js.cybozu.com/sweetalert2/v8.2.1/sweetalert2.min.js
    • https://js.cybozu.com/sweetalert2/v8.2.1/sweetalert2.min.css
  • Moment.js v2.24.0, ドキュメント (External link)
    • https://js.cybozu.com/momentjs/2.24.0/moment-with-locales.min.js
  • ES6-Promise v4.0.5, ドキュメント (External link)
    • https://js.cybozu.com/es6-promise/v4.0.5/es6-promise.auto.min.js
  • Garoon html/css/image-Kit for Customize, ドキュメント

手順1. プロキシ API 設定

手順の詳細は プロキシAPIの設定を追加する (External link) を参照してください。

  1. 「Garoon システム管理」画面を開きます。

  2. 「基本システムの管理」タブをクリックし、[API]を選択します。

  3. [プロキシ API の設定]をクリックします。

  4. [追加する]をクリックします。

  5. 以下の内容を入力します。入力が終わったら、[追加する]ボタンをクリックして、設定を追加します。

    項目
    ステータス 「有効」を選択します。
    プロキシコード GET_ONEDRIVE_PORTLET
    メソッド 「GET」を選択します。
    URL https://graph.microsoft.com/
  6. 4.〜の手順と同様に、POST 用のプロキシ API を設定します。

    項目
    ステータス 「有効」を選択します。
    プロキシコード POST_ONEDRIVE_PORTLET
    メソッド 「POST」を選択します。
    URL https://graph.microsoft.com/

手順2. 画像ファイルを画像アセットへ追加

ポートレットに表示するメールアイコンの画像ファイルを、画像アセットに保存します。
手順の詳細は 画像アセットの追加 (External link) を参照してください。

  1. 「Garoon システム管理」画面を開きます。

  2. 「各アプリケーションの管理」タブをクリックし、[画像アセット]を選択します。

  3. [画像アセット一覧]をクリックします。

  4. [画像アセットを追加する]をクリックします。

  5. 「category20.gif」と「file20.gif」の 2 つのファイルを登録します。入力が終わったら、[追加する]ボタンをクリックして画像を追加します。

    項目
    ファイル garoon-onedrive-portal-thumb.zip をダウンロードし、解凍したフォルダー内のファイルを追加します。
    ファイルキー
    • downloadmore20.gif に設定する値
      ONEDRIVE_ICON_DOWNLOAD
    • link_sub16.png に設定する値
      ONEDRIVE_ICON_LINK
    • category20.gif に設定する値
      ONEDRIVE_ICON_FOLDER
    • file20.gif に設定する値
      ONEDRIVE_ICON_FILE
  6. 画像アセット登録後の画像アセット一覧は次のようになります。

手順3. HTML ポートレットの作成・カスタマイズの適用

カスタマイズポートレットを作成します。
手順の詳細は HTMLポートレットの設定 (External link) を参照してください。

  1. 「Garoon システム管理」画面を開きます。

  2. 「各アプリケーションの管理」タブをクリックし、[ポータル]をクリックします。

  3. [HTML ポートレット]をクリックします。

  4. [HTML ポートレットを追加する]をクリックします。

  5. 以下の内容を入力します。入力が終わったら、[追加する]をクリックします。

    項目
    ポートレット名 任意の値を入力してください。
    この記事では、「OneDriveコンテンツ表示」とします。
    ポートレットの内容 「テキスト」を選択します。
    内容は後述の サンプルコード(ポートレット HTML) を入力してください。
  6. 追加した「HTML ポートレットの詳細」画面で、[JavaScript / CSS によるカスタマイズ]をクリックします。

  7. 次のように入力します。入力が終わったら、[設定する]ボタンをクリックして設定します。

    項目
    カスタマイズ 「適用する」を選択します。
    JavaScript カスタマイズ 次の順で指定します。
    CSS カスタマイズ 次の順で指定します。
Microsoft Authentication Library for JavaScript(msal.min.js)の入手方法
  1. GitHub リポジトリ (External link) にアクセスします。
  2. [Source code(zip)]から zip ファイルをダウンロードします(バージョンは 0.1.2 を利用します)
  3. zip ファイルを解凍します。
  4. 解凍したフォルダーの「out」フォルダー以下の「msal.min.js」を利用します。
Garoon html/css/image-Kit for Customize の入手方法
  1. GitHub リポジトリ (External link) にアクセスします。
  2. [Clone or download]ボタンをクリックして、「Download ZIP」を選択します。
  3. ダウンロードした zip ファイルを解凍します。
  4. 解凍したファイルの「css」フォルダー以下の「grn_kit.css」を利用します。

手順4. ポータルへの配置

手順の詳細は ポートレットの配置 (External link) を参照してください。

  1. 「Garoon システム管理」画面を開きます。
  2. 「各アプリケーションの管理」タブをクリックし、[ポータル]をクリックします。
  3. [ポータルの一覧]をクリックします。
  4. 作成したポートレットを配置したいポータル名をクリックします。
    ポータルを新規に作る場合は、 ポータルの追加 (External link) を参考に作成してください。
  5. 左メニューのポートレット一覧から、作成したポートレット(OneDrive コンテンツ表示)を、右側のレイアウトにドラッグして配置します。
  6. 配置したポートレット右上の「未公開」ボタンをクリックして「公開中」に変更します。

動作確認

Office 365 OneDrive へのサインインとファイル一覧の表示

  1. Garoon で、カスタマイズした HTML ポートレットを配置したポータルを開きます。
  2. サインインを求めるダイアログが表示されます。
    OneDrive を利用しているアカウントでサインインします。
    「ポップアップウィンドウをブロックする」設定がされている場合、サインインのポップアップが表示されずにエラーメッセージが表示されます。
    その場合は、ブロック設定を解除した後、ポートレットの[OneDrive コンテンツ一覧を表示する]ボタンをクリックすると、サインインのダイアログを再表示できます。
  3. Garoon のポータルに OneDrive のファイル一覧が表示されます。

OneDrive へのファイル追加

  1. Garoon ポータルを表示します(Garoon ポータル上で OneDrive へサインイン済み)
  2. [ファイルを追加する]ボタンをクリックしダイアログからファイルを選択、または、追加したいファイルを[ファイルを追加する]ボタンにドラッグ&ドロップします。
  3. 追加対象のファイルが表示されます。[追加]ボタンをクリックすると、ファイルが追加されます。

サンプルコード

ポートレットHTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!--
* OneDrive Content Portlet sample program
* Copyright (c) 2019 Cybozu
*
* Licensed under the MIT License
-->

<div>
  <div id="od-portlet" style="display: none;">
    <div id="od-portlet-title">
      <span>
        <a href="" target="_blank" id="od-portlet-title-text">
          OneDrive
        </a>
      </span>
    </div>
    <div>
      <table id="od-portlet-list">
        <colgroup></colgroup>
        <thead></thead>
        <tbody id="od-portlet-contents"></tbody>
      </table>
      <div id="od-portlet-zero" style="display: none;">
        <span>アップロードされている フォルダ/ファイル はありません。</span>
      </div>
    </div>
    <div id="od-upload">
      <div id="od-upload-area">
        <div id="od-upload-input">
          <label id="od-upload-text" for="od-file-select" class="button_normal_grn_kit">+ファイルを追加する</label>
          <input type="file" id="od-file-select" multiple>
        </div>
        <div id="od-upload-add" style="display: none;">ここにファイルを追加</div>
      </div>
      <div id="od-uploaded" style="display: none;">
        <table class="list_table_style1_grn_kit">
          <colgroup>
            <col>
            <col>
          </colgroup>
          <thead>
            <tr>
              <th class="nowrap_grn_kit">ファイル名</th>
              <th class="nowrap_grn_kit">サイズ</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>

        <div id="od-upload-button" class="margin_t10_grn_kit">
          <button id="od-upload-button-add" class="button_main_sub_grn_kit">追加</button>
          <button id="od-upload-button-cancel" class="button_normal_sub_grn_kit">キャンセル</button>
        </div>
      </div>
    </div>
  </div>
  <div id="od-login" class="button_main_grn_kit" style="display: none;">
    <span id="od-login-text">OneDrive コンテンツ一覧を表示する</span>
  </div>
</div>

onedrive_contents_portlet.js

11 行目の CLIENT_ID を、 Microsoft Entra ID の設定:アプリケーションの作成 でメモした「アプリケーション(クライアント)ID」に変更してください。

次の値は、必要に応じて変更してください。

  • 27 行目 FOLDER_PATH:ファイル一覧として表示するフォルダーのパスです。絶対パスで指定します。
    例:フォルダーのパスが ファイル > meeting > 2019 なら、「/meeting/2019」を指定します。
  • ポータルのファイル一覧に表示する内容
    • 31 行目 MAX_NUMBER_OF_DISPLAY:ファイル/フォルダー表示数です。数字で指定します。
    • 33 行目 UPDATE_USER:「更新者」列の表示設定です。false を設定すると列を非表示にします。
    • 35 行目 UPDATE_TIME:「更新日時」列の表示設定です。false を設定すると列を非表示にします。
    • 37 行目 SIZE:「サイズ」列の表示設定です。false を設定すると列を非表示にします。
    • 39 行目 FOLDER:「フォルダー」列の表示設定です。false を設定すると列を非表示にします。
    • 41 行目 SHOW_LOGIN_POPUP:ポートレット表示時に OneDrive へサインインするポップアップの表示設定です。false を設定すると列を非表示にします。
      Outlook の未読メール数を表示するポートレット を追加している場合、false に設定してください。
    • 43 行目 THUMBNAIL:サムネイル表示の設定です。false を設定するとリスト形式で表示します。
      また、サムネイル形式で表示したときの表示数は以下で設定できます。
      • 45 行目 THUMBNAIL_COLUMNS:サムネイルの表示列数
      • 47 行目 THUMBNAIL_ROWS:サムネイルの表示行数
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
/*
 * OneDrive Content Portlet sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
*/

(function($) {
  'use strict';
  // azureAD で登録したアプリのアプリケーションID
  const CLIENT_ID = 'AZURE_APPLICATION_CLIENT_ID';
  // 画像アセットのファイルキー
  const ASSET_KEY = {
    // フォルダーアイコン
    FOLDER: 'ONEDRIVE_ICON_FOLDER',
    // ファイルアイコン
    FILE: 'ONEDRIVE_ICON_FILE',
    // ダウンロードアイコン
    DOWNLOAD: 'ONEDRIVE_ICON_DOWNLOAD',
    // リンクアイコン
    LINK: 'ONEDRIVE_ICON_LINK'
  };
  // プロキシコード
  const API_KEY_GET = 'GET_ONEDRIVE_PORTLET';
  const API_KEY_POST = 'POST_ONEDRIVE_PORTLET';
  // 表示する OneDrive のフォルダーパス
  const FOLDER_PATH = '';

  const CONFIG = {
    // 表示するファイル/フォルダ最大数
    MAX_NUMBER_OF_DISPLAY: 5,
    // 「更新者」を表示する
    UPDATE_USER: true,
    // 「更新日時」を表示する
    UPDATE_TIME: true,
    // 「サイズ」を表示する
    SIZE: true,
    // フォルダを表示する
    FOLDER: true,
    // 表示時にログインポップアップを表示する
    SHOW_LOGIN_POPUP: true,
    // サムネイル表示にする
    THUMBNAIL: true,
    // サムネイルの表示列数
    THUMBNAIL_COLUMNS: 3,
    // サムネイルの表示行数
    THUMBNAIL_ROWS: 2
  };

  const SA = {
    sa: Swal,
    loading: function() {
      this.sa.fire({
        title: '処理中です...',
        type: 'info',
        allowOutsideClick: false,
        allowEscapeKey: false,
        showConfirmButton: false
      });
    },
    uploading: function() {
      return this.sa.fire({
        title: 'アップロード中です',
        type: 'info',
        html: (
          '<div>完了までしばらくお待ちください。</div>' +
          '<div>' +
          '<span id="od-uploading"></span>' +
          '<span>件 処理終了</span>' +
          '<div>' +
          '<div id="od-uploading-errors"></div>'
        ),
        allowOutsideClick: false,
        allowEscapeKey: false,
        showConfirmButton: false
      });
    },
    warning: function(message) {
      return this.sa.fire({
        title: '警告',
        type: 'warning',
        html: message || ''
      });
    },
    error: function(message) {
      return this.sa.fire({
        title: 'OneDriveポートレット表示中に<br>エラーが発生しました',
        type: 'error',
        html: message || '画面を更新してください。'
      });
    },
    close: function() {
      this.sa.close();
    }
  };

  const UTIL = {
    convertUnits: function(value) {
      const convert = {
        unit: 'B',
        size: 0
      };
      const UNITS = [
        {
          unit: 'GB',
          size: 1000000000
        },
        {
          unit: 'MB',
          size: 1000000
        },
        {
          unit: 'KB',
          size: 1000
        },
        {
          unit: 'B',
          size: 1
        }
      ];
      for (let i = 0; i < UNITS.length; i++) {
        if (value >= UNITS[i].size) {
          convert.size = Math.round(value / UNITS[i].size);
          convert.unit = UNITS[i].unit;
          break;
        }
      }
      return convert;
    },
    isPopupWindow: function() {
      return /id_token|error/.test(location.hash);
    },
    closeAlertOrShowErrorAlert: function(error) {
      if (/user_cancelled|access_denied/.test(error)) {
        SA.close();
      } else {
        SA.error(error);
      }
    }
  };

  const ContentsListMaker = function() {
    if (!(this instanceof ContentsListMaker)) {
      return new ContentsListMaker();
    }

    this.onedriveClient = new OnedriveClient();
    this.$contentsList = $('#od-portlet-contents');
    this.uploadFiles = [];
    this.divideContents = {};
    this.assets = {
      file: garoon.assets.images.getUrl(ASSET_KEY.FILE),
      folder: garoon.assets.images.getUrl(ASSET_KEY.FOLDER),
      download: garoon.assets.images.getUrl(ASSET_KEY.DOWNLOAD),
      link: garoon.assets.images.getUrl(ASSET_KEY.LINK),
    };

    this.init = function() {
      const SELF = this;
      this.onedriveClient.setUserAgentApplication();
      return new Promise((resolve, reject) => {
        SELF.onedriveClient.login().then(() => {
          SELF.registerFileInput();
          SELF.registerDandDEvent();
          SELF.registerAddButtonEvent();
          SELF.registerCancelButtonEvent();
          SELF.onedriveClient.fetchDriveInfo().then((response) => {
            const DATA = JSON.parse(response);
            if ('error' in DATA) {
              reject(DATA.error.code + ':' + DATA.error.message);
            } else {
              SELF.setTitleInfo(DATA.webUrl);
              $('#od-login').hide();
              resolve();
            }
          }).catch((error) => {
            reject(error);
          });
        }).catch((error) => {
          reject(error);
        });
      });
    };
    this.setVideoSrc = function(id) {
      const SELF = this;
      return new Promise((resolve, reject) => {
        SELF.onedriveClient.fetchVideoUrl(id).then((response) => {
          $('#od-' + id).attr('src', response.getUrl);
          resolve(id);
        }).catch((error) => {
          reject({error: error, id: id});
        });
      });
    };
    this.getPopupWindowHtml = function(contentId, modalContent, attr) {
      return (
        '<div id="od-modal-' + contentId + '" class="od-thumbnail-modal" style="display: none;">' +
        '  <div class="od-thumbnail-modal-wrap">' +
        '    <span class="od-thumbnail-modal-close">×</span>' +
        modalContent +
        '    <div class="od-modal-footer">' +
        '      <div class="od-modal-footer-icons">' +
        '        <a class="od-modal-footer-icon od-modal-footer-download" href="' + attr.href + '" title="ファイルをダウンロードする">' +
        '          <img class="od-modal-footer-icon" src="' + this.assets.download + '" align="middle">ダウンロード' +
        '        </a>' +
        '        <div class="od-modal-footer-icon od-modal-footer-link od-thumbnail-link-icon" data-url="' +
        attr.webUrl + '" title="ファイルのリンクURLをコピーする">' +
        '          <img class="od-modal-footer-icon" src="' + this.assets.link + '" align="middle">リンクをコピー' +
        '        </div>' +
        '      </div>' +
        '    </div>' +
        '  </div>' +
        '</div>'
      );
    };
    this.getThumbnailTooltipText = function(content, contentSize) {
      return [
        '更新者:' + content.lastModifiedBy.user.displayName,
        '更新日時:' + moment(content.lastModifiedDateTime).locale('ja').format('YYYY年MM月DD日(ddd)'),
        'サイズ:' + contentSize
      ].join('\n');
    };
    this.getFileThumbnailHtml = function(tooltipText, content, hoverStyle, thumbnail, attr) {
      return (
        '<td class="od-thumbnail" title="' + tooltipText + '">' +
        '  <div class="od-thumbnail-wrap ' + hoverStyle + '" data-id="' + content.id + '">' +
        '    <div class="od-thumbnail-icon">' + thumbnail + '</div>' +
        '    <div class="od-thumbnail-name">' +
        '      <span>' + content.name + '</span>' +
        '    </div>' +
        '  </div>' +
        '  <div class="od-thumbnail-download">' +
        '    <a href="' + attr.href + '">' +
        '      <img title="ダウンロードする" src="' + this.assets.download + '">' +
        '    </a>' +
        '    <div id="od-thumbnail-link-' + content.id + '" class="od-thumbnail-link-icon" target="_brank" data-url="' + attr.webUrl + '">' +
        '      <img style="margin-left: 5px;" title="ファイルURLをコピーする" src="' + this.assets.link + '">' +
        '    </div>' +
        '  </div>' +
        '</td>'
      );
    };
    this.getFolderThumbnailHtml = function(tooltipText, content, thumbnail, attr) {
      return (
        '<td class="od-thumbnail" title="' + tooltipText + '">' +
        '  <a href="' + attr.href + '" ' + attr.target + '>' +
        '    <div class="od-thumbnail-icon">' + thumbnail + '</div>' +
        '    <div class="od-thumbnail-name">' +
        '      <span>' + content.name + '</span>' +
        '    </div>' +
        '  </a>' +
        '  <div class="od-thumbnail-download"><br></div>' +
        '</td>'
      );
    };
    this.getThumbnailPortletHtml = function(contents) {
      const SELF = this;
      const THUMBNAIL_WIDTH = 230;
      const thumbnailDiv = '<tr class="od-portlet-contents-throw" style="width: ' + THUMBNAIL_WIDTH * CONFIG.THUMBNAIL_COLUMNS + 'px;">';
      const thumbnailContents = {
        items: thumbnailDiv,
        modals: '',
        videoIds: [],
        number: 0
      };
      let contentSize = '';
      let addingColumn = true;
      $.each(contents, (index, content) => {
        if (index >= CONFIG.MAX_NUMBER_OF_DISPLAY) {
          return false;
        }
        thumbnailContents.number++;
        if (!addingColumn) {
          thumbnailContents.items += thumbnailDiv;
          addingColumn = true;
        }
        const attr = {
          href: '',
          target: '',
          webUrl: ''
        };
        let thumbnail = '';
        let modalContent = '';
        const IS_FILE_CONTENT = 'file' in content;
        let hoverStyle = 'od-thumbnail-wrap-hover';
        // ファイルの場合
        if (IS_FILE_CONTENT) {
          attr.href = content['@microsoft.graph.downloadUrl'];
          attr.webUrl = content.webUrl;
          contentSize = UTIL.convertUnits(content.size).size + ' ' + UTIL.convertUnits(content.size).unit;
          if (/video/.test(content.file.mimeType)) {
            // 動画ファイルの場合、iframe上に動画フォームを作成する
            thumbnail = '<img class="od-thumbnail-icon-img" src="' + content.thumbnails[0].medium.url + '">';
            modalContent = '<iframe class="od-thumbnail-icon-modal od-thumbnail-icon-modal-video" id="od-' + content.id + '" src=""></iframe>';
            thumbnailContents.videoIds.push(content.id);
          } else if (content.thumbnails.length === 0) {
            thumbnail = '<img class="od-thumbnail-icon-file" src="' + SELF.assets.file + '">';
            hoverStyle = '';
          } else {
            thumbnail = (
              '<img class="od-thumbnail-icon-img od-thumbnail-icon-other" src="' + content.thumbnails[0].medium.url + '">'
            );
            modalContent = (
              '<div class="od-thumbnail-icon-wrap">' +
              '  <img class="od-thumbnail-icon-modal" src="' + content.thumbnails[0].large.url + '">' +
              '</div>'
            );
          }
        } else if ('folder' in content) {
          attr.href = content.webUrl;
          attr.target = 'target="_blank"';
          thumbnail = '<img class="od-thumbnail-icon-folder" src="' + SELF.assets.folder + '">';
          contentSize = content.folder.childCount + ' 個のアイテム';
        }
        if (modalContent !== '') {
          thumbnailContents.modals += SELF.getPopupWindowHtml(content.id, modalContent, attr);
        }
        const tooltipText = SELF.getThumbnailTooltipText(content, contentSize);
        if (IS_FILE_CONTENT) {
          thumbnailContents.items += SELF.getFileThumbnailHtml(tooltipText, content, hoverStyle, thumbnail, attr);
        } else {
          thumbnailContents.items += SELF.getFolderThumbnailHtml(tooltipText, content, thumbnail, attr);
        }
        if (addingColumn && (index + 1) % CONFIG.THUMBNAIL_COLUMNS === 0) {
          thumbnailContents.items += '</tr>';
          addingColumn = false;
        }
      });
      if (addingColumn) {
        thumbnailContents.items += '</div>';
      }
      return thumbnailContents;
    };
    this.makeThumbnail = function() {
      const SELF = this;
      const THUMBNAIL_HEIGHT = 275;
      // 更新時刻でソートする
      const sortedContetns = this.getSortedContentsByDateTime();
      const thumbnailContents = this.getThumbnailPortletHtml(sortedContetns);
      const $portlet = $('#od-portlet');
      $portlet.find('.od-thumbnail-modal').remove();
      $portlet.append(thumbnailContents.modals);
      SELF.$contentsList.html(thumbnailContents.items).ready(() => {
        $('.od-thumbnail-link-icon').on('click', function() {
          const $this = $(this);
          const hasModalFooterLink = $this.hasClass('od-modal-footer-link');
          const styleClass = hasModalFooterLink ? 'od-thumbnail-link-icon-tooltip-modal' : 'od-thumbnail-link-icon-tooltip-normal';
          const url = $this.data('url');
          $('body').append('<textarea id="od-thumbnail-clipboard">' + decodeURIComponent(url) + '</textarea>');
          const $clipboard = $('#od-thumbnail-clipboard');
          $clipboard.select();
          document.execCommand('copy');
          $clipboard.remove();
          const $tooltip = $('<div class="od-thumbnail-link-icon-tooltip ' + styleClass + '">クリップボードへコピーしました</div>');
          $this.append($tooltip).ready(() => {
            setTimeout(() => {
              $tooltip.remove();
            }, 1500);
          });
        });
        SELF.registerModalControllEvents();
        if (thumbnailContents.videoIds.length > 0) {
          const promiseall = [];
          thumbnailContents.videoIds.forEach((id) => {
            promiseall.push(SELF.setVideoSrc(id));
          });
          Promise.all(promiseall).catch((error) => {
            console.error(error);
          });
        }
        // スクロールバーをつける(2行以上表示する場合)
        if (thumbnailContents.number > CONFIG.THUMBNAIL_COLUMNS * CONFIG.THUMBNAIL_ROWS) {
          $('#od-portlet-list').addClass('od-thumbnail-table').height(THUMBNAIL_HEIGHT * CONFIG.THUMBNAIL_ROWS);
        }
        $portlet.show();
      });
    };
    this.showContentsList = function() {
      const SELF = this;
      this.onedriveClient.fetchContentsList().then((response) => {
        const respJson = JSON.parse(response);
        if ('error' in respJson) {
          if (respJson.error.code === 'itemNotFound') {
            throw new Error('指定したフォルダが見つかりませんでした。<br>フォルダパスの設定をご確認ください。');
          } else {
            throw new Error(respJson.error.code + ':' + respJson.error.message);
          }
        }
        SELF.divideContents = SELF.divideContentsByCategory(respJson.value);
        if (CONFIG.THUMBNAIL) {
          SELF.makeThumbnail();
        } else {
          SELF.setItemElements(respJson.value.length);
          SELF.makeContentsList();
        }
        SA.close();
      }).catch((error) => {
        console.error(error);
        SA.error('コンテンツ一覧の表示に失敗しました。<br>' + (error || ''));
      });
    };
    this.setTitleInfo = function(webUrl) {
      $('#od-portlet-title-text').attr('href', webUrl);
    };
    this.getContentNameColumn = function(content) {
      const attr = {
        href: '',
        target: '',
        imgSrc: '',
        class: ''
      };
      if ('folder' in content) {
        attr.href = 'href="' + content.webUrl + '"';
        attr.target = 'target="_blank"';
        attr.imgSrc = this.assets.folder;
      } else {
        if (typeof content['@microsoft.graph.downloadUrl'] === 'undefined') {
          attr.class = 'one-drive-reset-link';
        } else {
          attr.href = 'href="' + content['@microsoft.graph.downloadUrl'] + '"';
        }
        attr.imgSrc = this.assets.file;
      }
      return (
        '<td class="od-portlet-name">' +
        ' <a ' + attr.href + ' class="' + attr.class + '" ' + attr.target + '>' +
        '  <img src="' + attr.imgSrc + '" alt="">' +
        content.name +
        ' </a>' +
        '</td>'
      );
    };
    this.getModifiedUserColumn = function(userName) {
      return (
        '<td class="od-portlet-content">' +
        ' <span>' +
        userName +
        ' </span>' +
        '</td>'
      );
    };
    this.getModifiedDateTimeColumn = function(datetime) {
      return (
        '<td class="od-portlet-content">' +
        ' <span>' +
        moment(datetime).locale('ja').format('YYYY年MM月DD日(ddd)') +
        ' </span>' +
        '</td>'
      );
    };
    this.getContentSizeColumn = function(content) {
      const CONVERT_UNIT = UTIL.convertUnits(content.size);
      let size;
      if ('folder' in content) {
        size = content.folder.childCount + ' 個のアイテム';
      } else {
        size = (CONVERT_UNIT.size > 0 ? CONVERT_UNIT.size : 1) + ' ' + CONVERT_UNIT.unit;
      }
      return (
        '<td class="od-portlet-content">' +
        ' <span>' + size + '</span>' +
        '</td>'
      );
    };
    this.setItemElements = function(contentsLength) {
      const $zeroFile = $('#od-portlet-zero');
      if (contentsLength > 0) {
        $zeroFile.hide();
        let count = 1;
        let headerRow = '<tr><th>コンテンツ名</th>';
        if (CONFIG.UPDATE_USER) {
          count++;
          headerRow += '<th>更新者</th>';
        }
        if (CONFIG.UPDATE_TIME) {
          count++;
          headerRow += '<th>更新日時</th>';
        }
        if (CONFIG.SIZE) {
          count++;
          headerRow += '<th>サイズ</th>';
        }
        headerRow += '</tr>';
        $('#od-portlet-list').css('width', '100%');
        $('#od-portlet-list thead').html(headerRow);
        let cols = '';
        const WIDTH = 100 / count;
        for (let i = 0; i < count; i++) {
          cols += '<col style="width: ' + WIDTH + '%">';
        }
        $('#od-portlet-list colgroup').html(cols);
      } else {
        $zeroFile.show();
      }
    };
    this.divideContentsByCategory = function(contents) {
      const divideContents = {
        folders: [],
        files: []
      };
      contents.forEach((content) => {
        if ('folder' in content) {
          if (CONFIG.FOLDER) {
            divideContents.folders.push(content);
          }
        } else {
          divideContents.files.push(content);
        }
      });
      return divideContents;
    };
    this.getSortedContentsByDateTime = function() {
      const sortContetns = function(val1, val2) {
        if (moment(val1.lastModifiedDateTime).isBefore(val2.lastModifiedDateTime)) {
          return 1;
        }
        if (moment(val1.lastModifiedDateTime).isAfter(val2.lastModifiedDateTime)) {
          return -1;
        }
        return 0;
      };
      this.divideContents.folders.sort(sortContetns);
      this.divideContents.files.sort(sortContetns);
      return this.divideContents.folders.concat(this.divideContents.files);
    };
    this.makeContentsList = function() {
      const SELF = this;
      let rows = '';
      const sortedContetns = this.getSortedContentsByDateTime();
      const LENGTH = sortedContetns.length > CONFIG.MAX_NUMBER_OF_DISPLAY ? CONFIG.MAX_NUMBER_OF_DISPLAY : sortedContetns.length;
      for (let i = 0; i < LENGTH; i++) {
        rows += '<tr>';
        rows += SELF.getContentNameColumn(sortedContetns[i]);
        if (CONFIG.UPDATE_USER) {
          rows += SELF.getModifiedUserColumn(sortedContetns[i].lastModifiedBy.user.displayName);
        }
        if (CONFIG.UPDATE_TIME) {
          rows += SELF.getModifiedDateTimeColumn(sortedContetns[i].lastModifiedDateTime);
        }
        if (CONFIG.SIZE) {
          rows += SELF.getContentSizeColumn(sortedContetns[i]);
        }
        rows += '</tr>';
      }
      this.$contentsList.html(rows).ready(() => {
        $('#od-portlet').show();
        SA.close();
      });
    };
    this.pushUploadFiles = function(uploadFiles) {
      const errorFiles = [];
      const LENGTH = uploadFiles.length;
      const fileNames = this.uploadFiles.map((file) => {
        return file.name;
      });
      for (let upFileIndex = 0; upFileIndex < LENGTH; upFileIndex++) {
        if (uploadFiles[upFileIndex].type === '') {
          errorFiles.push(uploadFiles[upFileIndex]);
        } else {
          const fileNameIndex = fileNames.indexOf(uploadFiles[upFileIndex].name);
          if (fileNameIndex >= 0) {
            this.uploadFiles[fileNameIndex] = uploadFiles[upFileIndex];
          } else {
            this.uploadFiles.push(uploadFiles[upFileIndex]);
          }
        }
      }
      if (errorFiles.length > 0) {
        let excludedContents = '';
        for (let errorFileIndex = 0; errorFileIndex < errorFiles.length; errorFileIndex++) {
          excludedContents += (
            ' <li>' + errorFiles[errorFileIndex].name + '</li>'
          );
        }
        SA.warning(
          '<div>以下のファイルはアップロード対象外の形式です。</div>' +
          '<ul id="od-excluded-contents">' +
          excludedContents +
          '</ul>'
        );
      }
    };
    this.getFilesByStatus = function(selectedFiles, uploadFiles) {
      const fileStatus = {
        warn: [],
        normal: []
      };
      const fileNames = uploadFiles.map((file) => {
        return file.name;
      });
      for (let i = 0; i < selectedFiles.length; i++) {
        if (fileNames.indexOf(selectedFiles[i].name) >= 0) {
          fileStatus.warn.push(selectedFiles[i]);
        } else {
          fileStatus.normal.push(selectedFiles[i]);
        }
      }
      return fileStatus;
    };
    this.checkDuplicateFileName = function(selectedFiles, uploadFiles) {
      const files = this.getFilesByStatus(selectedFiles, uploadFiles);
      return new Promise((resolve, reject) => {
        if (files.warn.length > 0) {
          const title = (
            '<div class="od-fileupload-title">' +
            ' <div>同名のファイルが既に存在しています。</div>' +
            ' <div>置き換えますか?</div>' +
            '</div>'
          );
          let html = (
            '<div>' +
            ' <div class="od-fileupload-message">' +
            '置き換えるファイルを選択してください。' +
            ' </div>' +
            ' <div class="od-fileupload-warn">' +
            '  <div>' +
            '   <input id="od-fileupload-checkall" type="checkbox">' +
            '  </div>' +
            '  <div></div>' +
            ' </div>'
          );
          let warnFilesHtml = '';
          files.warn.forEach((file) => {
            warnFilesHtml += (
              '<div class="od-fileupload-warn">' +
              ' <div>' +
              '  <input class="od-fileupload-warn-checkbox" type="checkbox" value="' + file.name + '">' +
              ' </div>' +
              ' <div>' +
              '  <span>' + file.name + '</span>' +
              ' </div>' +
              '</div>'
            );
          });
          warnFilesHtml = '<div id="od-fileupload-files">' + warnFilesHtml + '</div>';
          html += warnFilesHtml + '</div>';
          const $html = $(html);
          Swal.fire({
            title: title,
            type: 'warning',
            confirmButtonText: 'する',
            cancelButtonText: 'しない',
            allowOutsideClick: false,
            allowEscapeKey: false,
            showConfirmButton: true,
            showCancelButton: true,
            html: $html,
            onOpen: function(dom) {
              const $dom = $(dom);
              const $warnFiles = $dom.find('input.od-fileupload-warn-checkbox');
              $dom.find('#od-fileupload-checkall').change(function() {
                $warnFiles.prop('checked', $(this).prop('checked'));
              });
            }
          }).then((result) => {
            const uploads = [];
            const checkResult = {};
            $('div.od-fileupload-warn input').each((index, warnFiles) => {
              $(warnFiles).each((fileIndex, file) => {
                const $file = $(file);
                checkResult[$file.val()] = {checked: $file.prop('checked')};
              });
            });

            for (let i = 0; i < selectedFiles.length; i++) {
              if (selectedFiles[i].name in checkResult) {
                if (checkResult[selectedFiles[i].name].checked) {
                  uploads.push(selectedFiles[i]);
                }
              } else {
                uploads.push(selectedFiles[i]);
              }
            }
            if (result.value) {
              resolve(uploads);
            } else if (files.normal.length > 0) {
              resolve(files.normal);
            }
            resolve([]);
          }).catch((error) => {
            console.error(error);
            reject(error);
          });
        } else {
          resolve(selectedFiles);
        }
      });
    };
    this.showUploadFileList = function() {
      const $upload = $('#od-uploaded');
      if (this.uploadFiles.length > 0) {
        let trs = '';
        this.uploadFiles.forEach((uploadFile) => {
          const CONVERT_UNIT = UTIL.convertUnits(uploadFile.size);
          trs += '<tr><td>' + uploadFile.name + '</td><td>' + CONVERT_UNIT.size + ' ' + CONVERT_UNIT.unit + ' </td></tr>';
        });
        $('#od-uploaded tbody').html(trs);
        $upload.show();
      } else {
        $upload.hide();
      }
    };
    this.registerCancelButtonEvent = function() {
      const SELF = this;
      $('#od-upload-button-cancel').on('click', () => {
        SELF.uploadFiles = [];
        SELF.showUploadFileList();
      });
    };
    this.registerAddButtonEvent = function() {
      const SELF = this;
      $('#od-upload-button-add').on('click', () => {
        SELF.checkDuplicateFileName(SELF.uploadFiles, SELF.divideContents.files).then((result) => {
          if (result.length > 0) {
            SA.uploading();
            SELF.onedriveClient.putFiles(result).catch((error) => {
              console.error(error);
            }).finally(() => {
              SELF.showContentsList();
              SELF.uploadFiles = [];
              SELF.showUploadFileList();
            });
          } else {
            SELF.uploadFiles = [];
            SELF.showUploadFileList();
          }
        });
      });
    };
    this.registerFileInput = function() {
      const SELF = this;
      $('#od-file-select').on('change', function(event) {
        const EVENT_SELF = this;
        const files = $('#od-file-select').prop('files');
        SELF.getFileContents(files).then((result) => {
          return SELF.checkDuplicateFileName(result, SELF.uploadFiles);
        }).then((result) => {
          SELF.pushUploadFiles(result);
          SELF.showUploadFileList();
          $(EVENT_SELF).val('');
        });
      });
    };
    this.registerDandDEvent = function() {
      const SELF = this;
      const $uploadInput = $('#od-upload-input');
      const $uploadAdd = $('#od-upload-add');
      const $uploadArea = $('#od-upload-area');
      let dragControlFlag = false;
      let isDragover = false;
      $('#od-upload-area').on({
        dragenter: function() {
          dragControlFlag = true;
        },
        dragover: function(event) {
          event.preventDefault();
          if (!isDragover) {
            $uploadInput.hide();
            $uploadAdd.show().addClass('od-upload-drag-in');
            $uploadArea.css('width', '100%');
            isDragover = true;
            dragControlFlag = false;
          }
        },
        dragleave: function(event) {
          event.preventDefault();
          if (dragControlFlag) {
            dragControlFlag = false;
          } else {
            $uploadInput.show();
            $uploadAdd.hide().removeClass();
            $uploadArea.css('width', '');
            isDragover = false;
          }
        },
        drop: function(event) {
          event.preventDefault();
          $uploadInput.show();
          $uploadAdd.hide().removeClass();
          $uploadArea.css('width', '');
          isDragover = false;
          dragControlFlag = false;
          const files = event.originalEvent.dataTransfer.files;
          SELF.getFileContents(files).then((result) => {
            return SELF.checkDuplicateFileName(result, SELF.uploadFiles);
          }).then((result) => {
            SELF.pushUploadFiles(result);
            SELF.showUploadFileList();
          }).catch((e) => {
            console.error(e);
          });
        }
      });
    };
    this.registerModalControllEvents = function() {
      const SELF = this;
      $('div.od-thumbnail-wrap').on('click', function() {
        const $this = $(this);
        if ($this.find('.od-thumbnail-icon-other').data('status') !== 'error') {
          const id = '#od-modal-' + $this.data('id');
          $(id).fadeIn('fast');
        }
      });
      $('div.od-thumbnail-modal').on('click', function(event) {
        const $target = $(event.target);
        if (!($target.hasClass('od-thumbnail-icon-modal') || $target.hasClass('od-modal-footer-icon'))) {
          $(this).fadeOut('fast');
          const $video = $(this).find('.od-thumbnail-icon-modal-video');
          if ($video.length > 0) {
            const src = $video.attr('src');
            $video.attr('src', '').attr('src', src);
          }
        }
      });
      $('img.od-thumbnail-icon-other').on('error', function() {
        const $this = $(this);
        $this.removeClass('od-thumbnail-icon-img').addClass('od-thumbnail-icon-file');
        $this.attr({
          src: SELF.assets.file,
          'data-status': 'error'
        });
        const $parent = $this.parents('div.od-thumbnail-wrap');
        $parent.removeClass('od-thumbnail-wrap-hover');
      });
    };
    this.getFileContents = function(files) {
      const promiseAll = [];
      for (let i = 0; i < files.length; i++) {
        promiseAll.push(this.readFileContent(files[i]));
      }
      return Promise.all(promiseAll);
    };
    this.readFileContent = function(file) {
      return new Promise((resolve, reject) => {
        const fileInfo = {
          name: file.name,
          type: file.type
        };
        const reader = new FileReader();
        reader.onload = function(e) {
          resolve(new File([reader.result], fileInfo.name, {type: fileInfo.type}));
        };
        reader.onerror = function(error) {
          resolve({
            status: 'error',
            name: file.name,
            type: file.type,
            message: 'ファイルの内容を取得できませんでした。'
          });
        };
        reader.readAsArrayBuffer(file);
      });
    };
    this.setLoginForm = function() {
      const SELF = this;
      $('#od-login').show();
      const $login = $('#od-login span');
      $login.on('click', () => {
        sessionStorage.onedriveLoginBtn = 'clicked';
        SA.loading();
        SELF.init().then(() => {
          SELF.showContentsList();
        }).catch((error) => {
          UTIL.closeAlertOrShowErrorAlert(error);
        }).finally(() => {
          sessionStorage.removeItem('onedriveLoginBtn');
        });
      });
    };
  };

  const OnedriveClient = function() {
    if (!(this instanceof OnedriveClient)) {
      return new OnedriveClient();
    }

    this.contentsListMaker = null;
    this.clientId = CLIENT_ID;
    this.apiScopes = ['User.Read', 'Files.ReadWrite.All'];
    this.userAgentApplication = null;

    this.setUserAgentApplication = function() {
      this.userAgentApplication = new Msal.UserAgentApplication(
        this.clientId,
        null,
        null
      );
    };
    this.login = function() {
      const SELF = this;
      return new Promise((resolve, reject) => {
        if (SELF.userAgentApplication.getUser()) {
          resolve();
        } else {
          SELF.userAgentApplication.loginPopup(SELF.apiScopes).then(() => {
            resolve();
          }).catch((error) => {
            reject(error);
          });
        }
      });
    };
    this.fetchDriveInfo = function() {
      const SELF = this;
      return new Promise((resolve, reject) => {
        SELF.userAgentApplication.acquireTokenSilent(SELF.apiScopes).then((token) => {
          const PATH = encodeURIComponent(FOLDER_PATH !== '' ? '/root:/' + FOLDER_PATH : '');
          garoon.base.proxy.send(
            API_KEY_GET,
            'https://graph.microsoft.com/v1.0/me/drive' + PATH,
            'GET',
            {
              Authorization: 'Bearer ' + token
            },
            {},
            (response) => {
              resolve(response);
            },
            (error) => {
              reject(error);
            }
          );
        }).catch((error) => {
          reject('画面の更新または、再ログインしてください。<br>' + error);
        });
      });
    };
    this.fetchContentsList = function() {
      const SELF = this;
      return new Promise((resolve, reject) => {
        SELF.userAgentApplication.acquireTokenSilent(SELF.apiScopes).then((token) => {
          const PATH = encodeURIComponent(FOLDER_PATH === '' ? '' : ':/' + FOLDER_PATH + ':');
          garoon.base.proxy.send(
            API_KEY_GET,
            'https://graph.microsoft.com/v1.0/me/drive/root' + PATH + '/children?$expand=thumbnails($select=medium,large)',
            'GET',
            {
              Authorization: 'Bearer ' + token
            },
            {},
            (response) => {
              resolve(response);
            },
            (error) => {
              reject(error);
            }
          );
        }).catch((error) => {
          reject(error);
        });
      });
    };
    this.fetchVideoUrl = function(id) {
      const SELF = this;
      return new Promise((resolve, reject) => {
        SELF.userAgentApplication.acquireTokenSilent(SELF.apiScopes).then((token) => {
          garoon.base.proxy.send(
            API_KEY_POST,
            'https://graph.microsoft.com/v1.0/me/drive/items/' + id + '/preview',
            'POST',
            {
              Authorization: 'Bearer ' + token,
              'Content-Type': 'application/json'
            },
            {},
            (response) => {
              resolve(JSON.parse(response));
            },
            (error) => {
              reject(error);
            }
          );
        }).catch((error) => {
          reject(error);
        });
      });
    };
    this.setUploadedFileNum = function(uploadedNum, total) {
      $('#od-uploading').text(uploadedNum + '/' + total);
    };
    this.putFiles = function(uploadFiles) {
      const SELF = this;
      const promiseall = [];
      const uploadedNum = {
        counter: 0
      };
      const TOTAL = uploadFiles.length;
      this.setUploadedFileNum(uploadedNum.counter, TOTAL);
      uploadFiles.forEach((uploadFile) => {
        promiseall.push(SELF.addFileToOnedirve(uploadFile, TOTAL, uploadedNum));
      });
      return Promise.all(promiseall);
    };
    this.getUploadParameter = function(arrayBuffer) {
      // 一度に送れる最大サイズ
      const SEND_MAX_SIZE = 60 * 1024 * 1024;
      const SEPARATOR = SEND_MAX_SIZE < arrayBuffer.byteLength ? SEND_MAX_SIZE : arrayBuffer.byteLength;
      const BUFFER_LENGTH = arrayBuffer.byteLength - 1;
      const sizePairs = [];
      for (let i = 0; i < arrayBuffer.byteLength; i += SEPARATOR) {
        sizePairs.push({
          start: i,
          end: BUFFER_LENGTH < i + SEPARATOR - 1 ? BUFFER_LENGTH : i + SEPARATOR - 1
        });
      }
      return sizePairs;
    };
    this.uploadFileToOneDrive = function(uploadUrl, fileName, accessToken, arrayBuffer, sizePairs, counter) {
      const SELF = this;
      return new Promise((resolve, reject) => {
        try {
          const uploadXhr = new XMLHttpRequest();
          uploadXhr.open('PUT', uploadUrl);
          uploadXhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
          uploadXhr.setRequestHeader(
            'Content-Range',
            'bytes ' + sizePairs[counter].start + '-' + sizePairs[counter].end + '/' + arrayBuffer.byteLength);
          uploadXhr.onload = function() {
            const next = counter + 1;
            if (next < sizePairs.length) {
              SELF.uploadFileToOneDrive(uploadUrl, fileName, accessToken, arrayBuffer, sizePairs, next).then(() => {
                resolve(uploadXhr);
              }).catch((error) => {
                console.error(error);
                reject(error);
              });
            } else {
              resolve(fileName);
            }
          };
          uploadXhr.onerror = function(error) {
            reject(error);
          };
          uploadXhr.send(new Uint8Array(arrayBuffer.buffer.slice(sizePairs[counter].start, sizePairs[counter].end + 1)));
        } catch (e) {
          console.error(e);
          const deleteXhr = new XMLHttpRequest();
          deleteXhr.open('DELETE', uploadUrl);
          deleteXhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
          deleteXhr.onload = function() {
            $('#od-uploading-errors').append(
              '<div>' +
              '  <div>アップロードに失敗しました</div><div>' + fileName + '</div>' +
              '</div>'
            );
            resolve(fileName);
          };
          deleteXhr.send();
        }
      });
    };
    this.addFileToOnedirve = function(uploadFile, total, uploadedNum) {
      const SELF = this;
      return new Promise((resolve, reject) => {
        SELF.userAgentApplication.acquireTokenSilent(SELF.apiScopes).then((token) => {
          const FILE_NAME = encodeURIComponent(
            FOLDER_PATH === '' ? uploadFile.name : FOLDER_PATH + '/' + uploadFile.name
          );
          const SESSION_URL = 'https://graph.microsoft.com/v1.0/me/drive/items/root:/' + FILE_NAME + ':/createUploadSession';
          const xhr = new XMLHttpRequest();
          xhr.open('POST', SESSION_URL);
          xhr.setRequestHeader('Authorization', 'Bearer ' + token);
          xhr.setRequestHeader('Content-Type', 'application/json');
          xhr.onload = function() {
            const reader = new FileReader();
            reader.readAsArrayBuffer(uploadFile);
            reader.onload = function() {
              const ARRAY_BUFFER = new Uint8Array(reader.result);
              const UPLOAD_URL = JSON.parse(xhr.response).uploadUrl;
              const SIZE_PAIRS = SELF.getUploadParameter(ARRAY_BUFFER);
              const counter = 0;
              SELF.uploadFileToOneDrive(UPLOAD_URL, uploadFile.name, token, ARRAY_BUFFER, SIZE_PAIRS, counter).then((response) => {
                uploadedNum.counter += 1;
                SELF.setUploadedFileNum(uploadedNum.counter, total);
                resolve(response);
              }).catch((error) => {
                reject(error);
              });
            };
          };
          xhr.onerror = function(error) {
            reject(error);
          };
          xhr.send(JSON.stringify({
            item: {
              '@microsoft.graph.conflictBehavior': 'replace',
              name: uploadFile.name
            }
          }));
        });
      });
    };
  };

  const main = function() {
    try {
      const contentsListMaker = new ContentsListMaker();

      if (UTIL.isPopupWindow()) {
        contentsListMaker.onedriveClient.setUserAgentApplication();
        return;
      }

      if (CONFIG.SHOW_LOGIN_POPUP || sessionStorage.getItem('onedriveLoginBtn') === 'clicked') {
        SA.loading();
        contentsListMaker.init().then(() => {
          contentsListMaker.showContentsList();
        }).catch((error) => {
          console.error(error);
          if (CONFIG.SHOW_LOGIN_POPUP) {
            contentsListMaker.setLoginForm();
          }
          UTIL.closeAlertOrShowErrorAlert(error);
        });
      } else {
        contentsListMaker.setLoginForm();
      }
    } catch (error) {
      console.error(error);
      SA.error('管理者へお問い合わせください。');
    }
  };
  main();
})(jQuery.noConflict(true));

onedrive_contents_portlet.css

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
 * OneDrive Content Portlet sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
*/

#od-portlet {
  background-color: white;
}

#od-portlet-title {
  border-bottom: 1px dashed #dbdbdb;
  padding-bottom: 5px;
  font-size: 16px;
}

#od-portlet-title-text {
  text-decoration: none;
  color: #248dd7;
}

#od-portlet-title-text:hover {
  color: #c30;
  text-decoration: underline;
}

#od-portlet-list {
  padding-bottom: 20px;
}

#od-portlet-list th {
  color: #666;
  font-size: 95%;
  font-weight: normal;
  text-align: left;
  padding-top: 10px;
  white-space: nowrap;
}

.od-portlet-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 0;
}

.od-portlet-name img {
  vertical-align: -4px;
  margin-right: 3px;
}

.od-portlet-contents-throw {
  display: block;
}

.od-portlet-content {
  font-size: 80%;
  white-space: nowrap;
}

#od-upload {
  margin: 10px 0 10px 0;
}

#od-upload-area {
  display: inline-block;
}

#od-upload-add {
  width: 100%;
}

.od-upload-drag-in {
  display: flex;
  width: 100%;
  height: 80px;
  border: 1px dashed #248dd7;
  background-color: #e0ffff;
  align-items: center;
  justify-content: center;
  margin: 5px 0 10px 0;
  font-size: 90%;
}

#od-uploaded {
  margin-top: 10px;
}

#od-uploaded-table {
  width: 100%;
  border-collapse: collapse;
}

#od-uploaded-table th {
  font-weight: normal;
  text-align: left;
  padding-left: 15px;
  border-bottom: 1px solid #d4d7dd;
  background-color: #eae9e9;
}

#od-uploaded-table td {
  padding-left: 15px;
  padding-top: 5px;
  padding-bottom: 5px;
  border-bottom: 1px solid #d4d7dd;
  font-size: 90%;
}

#od-uploaded-table col {
  width: 50%;
  border: 1px solid #d4d7dd;
}

#od-upload-input {
  color: #0a62ad;
}

#od-file-select {
  display: none;
}

#od-upload-text {
  display: inline-block;
}

#od-login span:hover {
  cursor: pointer;
}

#od-uploading-errors {
  font-size: 90%;
  width: 100%;
}

#od-uploading-errors > div {
  color: #dc143c;
  display: flex;
}

#od-uploading-errors > div > div:nth-child(1) {
  width: 50%;
  text-align: right;
}

#od-uploading-errors > div > div:nth-child(2) {
  width: 50%;
  text-align: left;
  padding-left: 3px;
}

#od-excluded-contents {
  text-align: left;
  margin-top: 10px;
}

.one-drive-reset-link:link,
.one-drive-reset-link:visited,
.one-drive-reset-link:hover {
  color: #333;
  text-decoration: none;
}

.od-fileupload-title {
  font-size: 24px;
}

#od-fileupload-files {
  max-height: 108px;
  overflow-y: scroll;
  margin-top: 5px;
}

.od-fileupload-warn {
  display: flex;
}

.od-fileupload-warn:nth-child(odd) {
  background-color: #efefef;
}

.od-fileupload-warn div:nth-child(1) {
  width: 10%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.od-fileupload-warn div:nth-child(2) {
  width: 90%;
}

.od-fileupload-warn input[type="checkbox"]:hover {
  cursor: pointer;
}

.od-thumbnail {
  display: inline-block;
  word-break: break-word;
  margin: 5px;
  padding: 5px;
}

.od-thumbnail:hover {
  background-color: #f0f8ff;
}

.od-thumbnail-table {
  display: block;
  overflow-y: scroll;
}

.od-thumbnail-icon {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 5px;
}

.od-thumbnail-icon-modal-video {
  width: 100%;
  height: 100%;
}

.od-thumbnail-wrap {
  display: inline;
  color: #0a62ad;
}

.od-thumbnail-wrap-hover:hover {
  cursor: pointer;
  color: #c30;
  text-decoration: underline;
}

.od-thumbnail-icon-video {
  width: 80%;
  height: 80%;
}

.od-thumbnail-icon-img {
  max-width: 100%;
  max-height: 100%;
  border: solid 1px #ccc;
}

.od-thumbnail-name {
  width: 200px;
  text-align: center;
}

.od-thumbnail-icon-file,
.od-thumbnail-icon-folder {
  max-width: 100%;
  height: 30%;
}

.od-thumbnail-download {
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.od-thumbnail-download img:hover {
  cursor: pointer;
  opacity: 0.6;
}

.od-thumbnail-modal {
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  background-color: rgba(0, 0, 0, 0.5);
  top: 0;
  left: 0;
  z-index: 1000;
  flex-direction: column;
}

.od-thumbnail-modal-wrap {
  width: 80%;
  height: 80%;
  color: white;
}

.od-thumbnail-icon-wrap {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.od-thumbnail-icon-wrap img {
  max-width: 100%;
  max-height: 100%;
}

.od-thumbnail-modal-close {
  display: inline-block;
  width: 75px;
  height: 75px;
  position: absolute;
  top: 50px;
  right: 30px;
  text-align: center;
  font-size: 50px;
  cursor: pointer;
  background-color: rgba(0,0,0,0.5);
  border-radius: 10px;
}

.od-thumbnail-modal-close:hover {
  background-color: rgba(0,0,0,0.8);
}

.od-thumbnail-link-icon {
  display: inline;
  position: relative;
}

.od-thumbnail-link-icon-tooltip {
  position: absolute;
  display: flex;
  color: white;
  background-color: #0a62ad;
  z-index: 5000;
  width: 180px;
  height: 2.0em;
  font-size: 11px;
  justify-content: center;
  align-items: center;
  border-radius: 8px 8px 8px 8px;
}

.od-thumbnail-link-icon-tooltip-normal {
  top: 30px;
  left: -90px;
}

.od-thumbnail-link-icon-tooltip-modal {
  top: 50px;
  left: -80px;
}

#od-thumbnail-clipboard {
  position: fixed;
  left: -100%;
}

.od-modal-footer {
  min-height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
}

.od-modal-footer-icons {
  display: flex;
  justify-content: center;
  background-color: #333;
  border-radius: 5px;
  height: 3em;
  margin-top: 5px;
}

a.od-modal-footer-download,
.od-modal-footer-link {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: white;
  padding: 8px;
}

a.od-modal-footer-download:hover,
.od-modal-footer-link:hover {
  background-color: #444;
}

a.od-modal-footer-download:hover {
  text-decoration: none;
  border-radius: 5px 0 0 5px;
}

.od-modal-footer-link:hover {
  border-radius: 0 5px 5px 0;
}

/* sweet alert のボタンデザイン修正 */
.swal2-confirm.swal2-styled,
.swal2-cancel.swal2-styled {
  padding: 0;
  width: 90px;
  height: 35px;
}

button.swal2-confirm.swal2-styled {
  padding: 0;
}

おわりに

この記事では、OneDrive 内のファイルの一覧を表示したり、ポータル上から OneDrive へファイル追加できるポートレットカスタマイズを紹介しました。
他にも cybozu developer network では、さまざまな Garoon ポータルカスタマイズ を紹介しています。ぜひ参照してください。

このカスタマイズでは次の API を利用しています。

変更履歴

このカスタマイズは、サイボウズ オフィシャル SI パートナー クロス・ヘッド株式会社による有償サポートの対象カスタマイズです。
詳細は サイボウズ製品 API 開発サポート (External link) を参照してください。

information

この Tips は、2019 年 9 月版 Garoon で動作を確認しています。