summaryrefslogtreecommitdiff
path: root/src/utils.c
blob: f004aa4f4b184ad9bd308cecd5e73f1147d7da72 (plain)
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
#include "../include/utils.h"
#include "../include/video.h"
#include "../libs/curl.h"
#include "../libs/string.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define JSONVAR "ytInitialData = "

char *
queryNormalizer (char *query)
{
	char *norm = NULL;
	if (query != NULL && strlen (query) > 0)
	{
		// Declaring Initial Query Size
		int querySize = strlen (query);

		// Calculating Normalized Query Size Allocation
		for (int i = 0; i < strlen (query); i++)
		{
			if (query[i] == '+' || query[i] == '#' || query[i] == '&')
			{
				querySize += 2;
			}
		}

		// Allocating Memory
		norm = (char *)calloc (querySize + 1, sizeof (char));

		// Creating New Normalized Query
		for (int i = 0, added = 0; i < strlen (query); i++)
		{
			switch (query[i])
			{
				case '+':
					/* fall through */
				case '#':
					/* fall through */
				case '&':
					for (int j = 0; j < 3; j++)
					{
						switch (j)
						{
							case 0:
								norm[i + j + added] = '%';
								break;
							case 1:
								norm[i + j + added] = '2';
								break;
							case 2:
								switch (query[i])
								{
									case '+':
										norm[i + j + added] = 'B';
										break;
									case '#':
										norm[i + j + added] = '3';
										break;
									case '&':
										norm[i + j + added] = '6';
								}
						}
					}
					added += 2;
					break;
				case ' ':
					norm[i + added] = '+';
					break;
				default:
					norm[i + added] = query[i];
			}
		}
	}
	return norm;
}

char *
extractQueryJSON (char *youtubeurl)
{
	char *json = NULL;

	if (youtubeurl != NULL && strlen (youtubeurl) > 0)
	{
		char *htmlPage = downloadPage (youtubeurl);
		if (htmlPage != NULL && strlen (htmlPage) > 0)
		{
			char *jsonVar = strstr(htmlPage, JSONVAR) + strlen(JSONVAR);
			if ( jsonVar != NULL && strlen(jsonVar) > 0 )
			{
				json = (char *) calloc(strlen(jsonVar) + 1, sizeof(char));
				strcpy(json, jsonVar);
			}
		}
		free (htmlPage);
	}
	return json;
}

int
checkNumber (char *num)
{
	int number = 0, charCheck = 1;

	if (num != NULL && strlen (num) > 0 && strlen (num) < 3)
	{
		for (int i = 0; i < strlen (num) && charCheck; i++)
		{
			if (!isdigit (num[i]))
			{
				charCheck--;
			}
		}

		number = (charCheck) ? atoi (num) : 0;
	}

	return number;
}