summaryrefslogtreecommitdiff
path: root/playlist.c
blob: 8dda9137c9b7edc487ed3b59f89c4ccf992a8af4 (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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "plat.h"
#include "playlist.h"

void init_playlist(Playlist* p) {
	p->name[0] = 0;
	p->cnt = 0;
}

void playlist_rm(Playlist* p, int i) {
	int j;
	for (j = i + 1; j < p->cnt; j++) {
		p->songs[j - 1] = p->songs[j];
	}
	p->cnt--;
}

void playlist_add(Playlist* p, Song* s) {
	if (p->cnt >= playlist_max)
		return;
	p->songs[p->cnt++] = s;
}

void playlist_add_first(Playlist* p, Song* s) {
	int i;
	if (p->cnt >= playlist_max)
		return;
	for (i = p->cnt - 1; i >= 0; i--) {
		p->songs[i + 1] = p->songs[i];
	}
	p->songs[0] = s;
	p->cnt++;
}

void playlist_shuffle(Playlist* p) {
	int ci, ri;
	Song* t;
	for (ci = p->cnt; ci;) {
		ri = rand() % ci;
		ci--;
		t = p->songs[ci];
		p->songs[ci] = p->songs[ri];
		p->songs[ri] = t;
	}
}

void get_playlist_dir(char* buf) {
	int llen;
	llen = strlen(library_path);
	strcpy(buf, library_path);
	if (buf[llen - 1] != '/')
		strcat(buf, "/");
	strcat(buf, "playlists/");
}

void playlist_save(const Playlist* p) {
	int i, plen, llen;
	const char* path, * ws;
	FILE* f;
	char wp[256];
	llen = strlen(library_path);
	get_playlist_dir(wp);
	if (!dir_exist(wp))
		if (!make_dir(wp)) return;
	strcat(wp, p->name);
	strcat(wp, ".m3u");
	f = fopen(wp, "w");
	if (!f) return;
	for (i = 0; i < p->cnt; i++) {
		path = p->songs[i]->path;
		plen = strlen(path);
		if (
			plen >= llen &&
			!memcmp(path, library_path, llen)
		)
			ws = path + llen;
		else
			ws = path;
		fputs(ws,   f);
		fputs("\n", f);
	}
	fclose(f);
}

int playlist_load(Library* l, Playlist* p, const char* name) {
	char path[256];
	char line[256];
	const char* sp;
	FILE* f;
	Song* s;
	int ll, lpl;
	lpl = strlen(library_path);
	get_playlist_dir(path);
	strcat(path, name);
	strcat(path, ".m3u");
	f = fopen(path, "r");
	if (!f) return 0;
	strcpy(p->name, name);
	p->cnt = 0;
	while (fgets(line, sizeof line, f)) {
		ll = strlen(line);
		for (
			;
			ll > 1 && line[ll - 1] == '\n';
			ll--, line[ll] = 0
		);
		if (strstr(line, library_path) != line) {
			strcpy(path, library_path);
			if (path[lpl - 1] != '/')
				strcat(path, "/");
			strcat(path, line);
			sp = path;
		} else {
			sp = line;
		}
		s = find_song(l, sp);
		if (s && s->path[0])
			playlist_add(p, s);
	}
	return 1;
}