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

const CookieInput = $(".CookieInput");
let NetflixJson;

CookieInput.keyup(function (e) {
    if (e.keyCode === 13) {
        $.ajax({
            url: "assets/php/getNetflixJson.php",
            data: {
                "Cookie": CookieInput.val()
            },
            type: "POST",
        }).done(function (response) {
            CookieInput.val("");
            AnalyzeData(response);
        });
    }
});

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 IndividualTitles = [];
    let IndividualSeries = [];
    let IndividualMovies = [];
    let AverageWatchTimes = [];

    NetflixJson.forEach(function (item, pageKey) {
        item.forEach(function (eachItem, ItemNumber) {
            if ("seriesTitle" in eachItem) { // is series
                const CurrentTitle = NetflixJson[pageKey][ItemNumber].seriesTitle;
                EveryWatched.push(CurrentTitle);
                if (IndividualSeries.indexOf(CurrentTitle) === -1 && CurrentTitle !== undefined) { // only if not already crawled -> individualism
                    IndividualSeries.push(CurrentTitle);
                    IndividualTitles.push(CurrentTitle);
                }
            } else { // is movie
                const CurrentTitle = NetflixJson[pageKey][ItemNumber].videoTitle;
                EveryWatched.push(CurrentTitle);
                if (IndividualMovies.indexOf(CurrentTitle) === -1 && CurrentTitle !== undefined) { // only if not already crawled -> individualism
                    IndividualMovies.push(CurrentTitle);
                    IndividualTitles.push(CurrentTitle);
                }
            }

            // get watch time
            const DayTimeInSeconds = new Date(NetflixJson[pageKey][ItemNumber].date * 1000);
            const DayTimeInHours = DayTimeInSeconds.getHours();
            AverageWatchTimes.push(DayTimeInHours);
        });
    });

    const TotalSeriesWatched = IndividualSeries.length;

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

    // Calculate the most watched series/movie
    let TitleCount = [];
    const UnsortedTitleOccurrenceCounter = EveryWatched.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {});
    const SortedTitleOccurrenceCounter = sortObject(UnsortedTitleOccurrenceCounter);

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

    RenderDayTimeChart(AverageWatchTimeOccurrence);
    RenderMostWatchedChart(SortedTitleOccurrenceCounter);
}

function RenderDayTimeChart(AverageWatchTimeOccurrenceArray) {
    var randomColorGenerator = function () {
        return '#' + (Math.random().toString(16) + '0000000').slice(2, 8);
    };

    // Render day time chart
    const WatchTimeChartElement = document.getElementById("WatchTimeChart").getContext("2d");
    const WatchTimeChart = 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
        }
    });
}

function RenderMostWatchedChart(TitleOccurrenceCounterObject) {
    // Render and calculate most watched chart

    const GenerateRandomColorArray = function () {
        let RandomColorArray = [];
        const Generate = function () {
            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: function (chart) {
            var data = chart.config.data;
            for (var key in TitleOccurrenceCounterObject) {
                if (TitleOccurrenceCounterObject.hasOwnProperty(key)) {
                    if (TitleOccurrenceCounterObject[key] > 2) {
                        data.labels.push(key);
                        data.datasets[0].data.push(TitleOccurrenceCounterObject[key]);
                    }
                }
            }
        }
    });
    var MostWatchedChart = new Chart(MostWatchedChartElement, {
        type: 'doughnut',
        data: MostWatchedChartData,
        options: {
            animation: {
                animateScale: true
            },
            legend: {
                display: false
            }
        }
    });
}

function sortObject(list) {
    var sortable = [];
    for (var key in list) {
        sortable.push([key, list[key]]);
    }
    sortable.sort(function (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;
}