aboutsummaryrefslogtreecommitdiff
path: root/assets/js/main.js
blob: 42ff881a2fc4da5a54ae0229eaf737ed7f1bad97 (plain) (blame)
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
/**
 * Clientside Script of the Netflix Stats Generator
 * @author Marvin Borner
 * @copyright Marvin Borner 2018
 */

$(() => {
  const DebuggingMode = true;
  const CookieInput = $(".CookieInput");
  let NetflixJson;

  moment.locale("de");
  moment().utcOffset(0); // offset for unix timestamp

  if (!DebuggingMode) {
    CookieInput.keyup(e => {
      if (e.keyCode === 13) {
        $.ajax({
          url: "assets/php/getNetflixJson.php",
          data: {
            Cookie: CookieInput.val()
          },
          type: "POST"
        }).done(response => {
          CookieInput.val("");
          CookieInput.hide();
          $(".Main").fadeIn();
          AnalyzeData(response);
        });
      }
    });
  } else {
    CookieInput.hide();
    $.ajax({
      url: "assets/js/ExampleData.js",
      type: "POST"
    }).done(response => {
      $(".Main").fadeIn();
      AnalyzeData(response);
    });
  }

  /**
   * Analyzes the Netflix data JSON response
   * @param {JSON} JsonResponse
   */
  function AnalyzeData(JsonResponse) {
    /**
     * @example response of a series:
     *  bookmark: 0
     *  country: "DE"
     *  date: 1529338765489
     *  dateStr: "18.06.18"
     *  deviceType: 1481
     *  duration: 3302
     *  episodeTitle: "Folge 13"
     *  estRating: "50"
     *  index: 0
     *  movieID: 80205354
     *  seasonDescriptor: "Teil 1"
     *  series: 80192098
     *  seriesTitle: "Haus des Geldes"
     *  title: "Teil 1: \"Folge 13\""
     *  topNodeId: "80192098"
     *  videoTitle: "Folge 13"
     *
     *  @example response of a movie:
     *  bookmark: 7771
     *  country: "DE"
     *  date: 1476477258019
     *  dateStr: "14.10.16"
     *  deviceType: 1193
     *  duration: 8160
     *  estRating: "30"
     *  index: 916
     *  movieID: 20557937
     *  title: "Matrix"
     *  topNodeId: "20557937"
     *  videoTitle: "Matrix"
     */
    NetflixJson = JSON.parse(JsonResponse);
    console.log(NetflixJson);
    let EveryWatched = [];
    let TitleWatchTime = {}; //how long you watched a series/movies
    let HeatmapDatesAll = [];
    let HeatmapDates = [];
    let IndividualTitles = [];
    let IndividualSeries = [];
    let IndividualMovies = [];
    let AverageWatchTimes = []; // when you watched a series/movie

    NetflixJson.forEach((item, pageKey) => {
      item.forEach((eachItem, ItemNumber) => {
        const currentObject = NetflixJson[pageKey][ItemNumber];
        let currentTitle; // will be overriden by 'if series'

        if ("seriesTitle" in eachItem) {
          // is series
          currentTitle = currentObject.seriesTitle;
          EveryWatched.push(currentTitle);
          if (
            IndividualSeries.indexOf(currentTitle) === -1 &&
            currentTitle !== undefined
          ) {
            // only if not already crawled -> individualism
            IndividualSeries.push(currentTitle);
          }
        } else {
          // is movie
          currentTitle = currentObject.videoTitle;
          EveryWatched.push(currentTitle);
          if (
            IndividualMovies.indexOf(currentTitle) === -1 &&
            currentTitle !== undefined
          ) {
            // only if not already crawled -> individualism
            IndividualMovies.push(currentTitle);
          }
        }

        // individualism check for every title
        if (
          IndividualMovies.indexOf(currentTitle) === -1 &&
          currentTitle !== undefined
        ) {
          if (!(IndividualTitles.includes(currentTitle))) IndividualTitles.push(currentTitle);

          // get watch-time in hours (how long you watched a series/movies)
          const watchTimeInHours = currentObject.duration / 60 / 60;
          let watchTime;
          if (currentTitle in TitleWatchTime) {
            // already in object -> add to previous
            const previousTitleWatchTime = TitleWatchTime[currentTitle];
            watchTime = watchTimeInHours + previousTitleWatchTime;
          } else {
            watchTime = watchTimeInHours;
          }
          TitleWatchTime[currentTitle] = watchTime;
        }

        // get watch time as date (when you watched a series/movie)
        const DayTimeInHours = Number(moment.unix(currentObject.date).format('HH'));
        AverageWatchTimes.push(DayTimeInHours);

        // get dates and push to heatmap date array for later duplicate deletion
        HeatmapDatesAll.push(currentObject.dateStr);
        // HeatmapDates.push({
        //   date: moment(currentObject.dateStr, 'DD.MM.YY').toDate(),
        //   count: 1
        // });
      });
    });

    // calculate count of dates for heatmap chart
    const HeatmapDatesOccurrenceCounter = new Map(
      [...new Set(HeatmapDatesAll)].map(x => [
        x,
        HeatmapDatesAll.filter(y => y === x).length // get length (=> occurrence) of filtered array
      ])
    );

    uniqueHeatmapDates = HeatmapDatesAll.filter(function (item, pos) {
      return HeatmapDatesAll.indexOf(item) == pos;
    });

    uniqueHeatmapDates.forEach((index, val) => {
      HeatmapDates.push({
        date: moment(uniqueHeatmapDates[val], 'DD.MM.YY').toDate(),
        count: HeatmapDatesOccurrenceCounter.get(uniqueHeatmapDates[val])
      });
    });


    const TotalSeriesWatched = IndividualSeries.length;

    // Calculate watch time occurrence (times in which the user watched sth.)
    let AverageWatchTimeOccurrence = [];
    const WatchTimeOccurrenceCounter = new Map(
      [...new Set(AverageWatchTimes)].map(x => [
        x,
        AverageWatchTimes.filter(y => y === x).length // get length (=> occurrence) of filtered array
      ])
    );
    for (let i = 0; i < 24; i++) {
      AverageWatchTimeOccurrence.push(WatchTimeOccurrenceCounter.get(i));
    }

    // Calculate the most watched series/movies
    const UnsortedTitleOccurrenceCounter = EveryWatched.reduce(
      (prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {}
    );
    const SortedTitleOccurrenceCounter = sortObject(
      UnsortedTitleOccurrenceCounter
    );
    const TopSeries = Object.keys(SortedTitleOccurrenceCounter)[
      Object.keys(SortedTitleOccurrenceCounter).length - 1
    ];

    // log
    console.table(IndividualTitles);
    console.table(IndividualSeries);
    console.table(IndividualMovies);
    console.table(AverageWatchTimeOccurrence);
    console.table(SortedTitleOccurrenceCounter);
    console.table(TitleWatchTime);

    // render
    RenderTopSeries(TopSeries);
    RenderDayTimeChart(AverageWatchTimeOccurrence);
    RenderMostWatchedChart(SortedTitleOccurrenceCounter, TitleWatchTime);
    RenderHeatmap(HeatmapDates);
  }

  /**
   * Renders the day time chart
   * @param {Array} AverageWatchTimeOccurrenceArray
   */
  function RenderDayTimeChart(AverageWatchTimeOccurrenceArray) {
    var randomColorGenerator = () => {
      return "#" + (Math.random().toString(16) + "0000000").slice(2, 8);
    };

    // Render day time chart
    const WatchTimeChartElement = document
      .getElementById("WatchTimeChart")
      .getContext("2d");
    new Chart(WatchTimeChartElement, {
      type: "line",
      data: {
        labels: [
          "12am",
          "1am",
          "2am",
          "3am",
          "4am",
          "5am",
          "6am",
          "7am",
          "8am",
          "9am",
          "10am",
          "11am",
          "12pm",
          "1pm",
          "2pm",
          "3pm",
          "4pm",
          "5pm",
          "6pm",
          "7pm",
          "8pm",
          "9pm",
          "10pm",
          "11pm"
        ],
        datasets: [{
          label: "Watches at daytime",
          borderColor: "rgb(255, 99, 132)",
          cubicInterpolationMode: "monotone",
          pointRadius: 0,
          pointHitRadius: 15,
          data: AverageWatchTimeOccurrenceArray
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              display: false
            },
            gridLines: {
              zeroLineColor: "transparent",
              zeroLineWidth: 2,
              drawTicks: false,
              drawBorder: false,
              color: "transparent"
            }
          }],
          xAxes: [{
            gridLines: {
              zeroLineColor: "rgba(255, 255, 255, 0.25)",
              display: true,
              drawBorder: false,
              color: "rgba(255, 255, 255, 0.25)"
            }
          }]
        },
        tension: 1
      }
    });
  }

  /**
   * Renders the "most watched series" doughnut chart
   * @param {Object} TitleOccurrenceCounterObject
   * @param {Object} TitleWatchTimeObject
   */
  function RenderMostWatchedChart(TitleOccurrenceCounterObject, TitleWatchTimeObject) {
    // Render and calculate most watched chart
    const GenerateRandomColorArray = () => {
      let RandomColorArray = [];
      const Generate = () => {
        var letters = "0123456789ABCDEF".split("");
        var color = "#";
        for (var i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
      };
      for (var key in TitleOccurrenceCounterObject) {
        RandomColorArray.push(Generate());
      }
      return RandomColorArray;
    };

    const MostWatchedChartElement = document
      .getElementById("MostWatchedChart")
      .getContext("2d");
    var MostWatchedChartData = {
      labels: [],
      datasets: [{
        label: "Most watched",
        backgroundColor: GenerateRandomColorArray(),
        data: []
      }]
    };
    Chart.pluginService.register({
      beforeInit: chart => {
        var data = chart.config.data;
        for (var key in TitleOccurrenceCounterObject) {
          if (TitleOccurrenceCounterObject.hasOwnProperty(key)) {
            if (TitleOccurrenceCounterObject[key] > 1) {
              data.labels.push(`${key} (Time: ${Math.round(TitleWatchTimeObject[key] * 100) / 100} hours)`); // add label with rounded watch time
              data.datasets[0].data.push(TitleOccurrenceCounterObject[key]);
            }
          }
        }
      }
    });
    new Chart(MostWatchedChartElement, {
      type: "doughnut",
      data: MostWatchedChartData,
      options: {
        animation: {
          animateScale: true,
          animateRotate: true
        },
        legend: {
          display: false
        }
      }
    });
  }

  /**
   * Renders the top series in the DOM
   * @param {String} Title
   */
  function RenderTopSeries(Title) {
    $.ajax({
      url: "assets/php/getInformation.php",
      data: {
        Title: Title
      },
      type: "POST"
    }).done(result => {
      const TopInformation = JSON.parse(result);
      $(".MostWatchedOverview > .MostWatchedPoster").attr(
        "src",
        `https://image.tmdb.org/t/p/w300${TopInformation.poster_path}`
      );
      $(".MostWatchedOverview > .Description").text(
        TopInformation.overview
      );
      console.log(TopInformation);
    });
  }

  /**
   * Renders a heatmap of all watched days
   * @param {Array} chartData
   */
  function RenderHeatmap(chartData) {
    const Heatmap = calendarHeatmap()
      .data(chartData)
      .selector('#Heatmap')
      .colorRange(['#ffd3d3', '#fc1111'])
      .tooltipEnabled(true)
      .onClick(function (data) {
        console.log('onClick callback. Data:', data);
      });

    Heatmap();
  }

  /**
   * Sorts an js object by value {int}
   * @param {Object} list
   */
  function sortObject(list) {
    var sortable = [];
    for (var key in list) {
      sortable.push([key, list[key]]);
    }
    sortable.sort((a, b) => {
      return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;
    });
    var orderedList = {};
    for (var i = 0; i < sortable.length; i++) {
      orderedList[sortable[i][0]] = sortable[i][1];
    }
    return orderedList;
  }
});