aboutsummaryrefslogtreecommitdiffstats
path: root/plugin_mysql.c
blob: 7372472d5e0126e7f8d038242c2a02a5b1c6c492 (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
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
/* $Id: plugin_mysql.c,v 1.3 2004/03/21 22:05:53 reinelt Exp $
 *
 * plugin for execute SQL queries into a MySQL DBSM.
 *
 * Copyright 2004 Javier Garcia <javi@gsmlandia.com>
 * Copyright 2004 The LCD4Linux Team <lcd4linux-devel@users.sourceforge.net>
 *
 * This file is part of LCD4Linux.
 *
 * LCD4Linux is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * LCD4Linux is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *
 * $Log: plugin_mysql.c,v $
 * Revision 1.3  2004/03/21 22:05:53  reinelt
 * MySQL plugin fixes from Javi
 *
 * Revision 1.2  2004/03/20 23:09:01  reinelt
 * MySQL plugin fixes from Javi
 *
 * Revision 1.1  2004/03/10 07:16:15  reinelt
 * MySQL plugin from Javier added
 *
 */

/* DOC:
 * To compile the plugin remember to add -lmysqlclient option into Makefile. I.E: CC = gcc -lmysqlclient 
 * or run:
 * $ gcc -I/usr/include/mysql -L/usr/lib/mysql plugin_mysql.c -lmysqlclient -o plugin_mysql.o
 *
 * exported functions:
 *
 * int plugin_init_mysql (void)
 *
 *  adds various functions:
 *     MySQLquery(query) 
 *        Returns the number of rows in query.
 *     MySQLstatus()
 *        Returns the current server status:
 *        Uptime in seconds and the number of running threads,
 *        questions, reloads, and open tables.
 *
 */

#include "config.h"
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "debug.h"
#include "plugin.h"
#include "cfg.h"

#ifdef HAVE_MYSQL_MYSQL_H
#include <mysql/mysql.h>
#else
#warning mysql/mysql.h not found: plugin deactivated
#endif

#ifdef WITH_DMALLOC
#include <dmalloc.h>
#endif


#ifdef HAVE_MYSQL_MYSQL_H
static MYSQL conex;

static char Section[] = "Plugin:MySQL";

static void my_MySQLquery (RESULT *result, RESULT *query)
{
  double value;
  MYSQL_RES *res;
  char *q=R2S(query);
  
  /* mysql_ping(MYSQL *mysql) checks whether the connection to the server is working.
     If it has gone down, an automatic reconnection is attempted. */
  mysql_ping(&conex);
  if (mysql_real_query(&conex,q,(unsigned int) strlen(q)))
  {
    error( "[MySQL] query error: %s",mysql_error(&conex));
    value=-1;
  }
  else
    {
    /* We don't use res=mysql_use_result();  because mysql_num_rows() will not
       return the correct value until all the rows in the result set have been retrieved
       with mysql_fetch_row(), so we use res=mysql_store_result(); instead */
    res=mysql_store_result(&conex);   
    value = (double) mysql_num_rows(res);
    mysql_free_result(res);
  }

  SetResult(&result, R_NUMBER, &value); 
}

static void my_MySQLstatus (RESULT *result)
{
  char *value;
  char *status;
  
  mysql_ping(&conex);
  status=strdup(mysql_stat(&conex));
  if (!status)
  {
    error( "[MySQL] status error: %s",mysql_error(&conex));
    value="error";
  }
  else value = status;
  
  SetResult(&result, R_STRING, value); 
}

#endif

int plugin_init_mysql (void)
{
#ifdef HAVE_MYSQL_MYSQL_H
  char server[256];
  unsigned int port;
  char user[128];
  char password[256];
  char database[256];  

  char *s = cfg_get (Section, "server", "localhost");
  if (*s=='\0') {
    info ("[MySQL] empty '%s.server' entry from %s, assuming 'localhost'", Section, cfg_source());
    strcpy(server,"localhost"); 
  }
  else strcpy(server,s);
  free(s);
  
  if (cfg_number(Section, "port", 0, 1, 65536, &port)<1) {
    /* using 0 as default port because mysql_real_connect() will convert it to real default one */
    info ("[MySQL] no '%s.port' entry from %s using MySQL's default", Section, cfg_source());
  }

  s = cfg_get (Section, "user", "");
  if (*s=='\0') {
    /* If user is NULL or the empty string "", the lcd4linux Unix user is assumed. */
    info ("[MySQL] empty '%s.user' entry from %s, assuming lcd4linux owner", Section, cfg_source());
    strcpy(user,""); 
  }
  else strcpy(user,s);
  free(s);   

  s = cfg_get (Section, "password","");
  /*Do not encrypt the password because encryption is handled automatically
   by the MySQL client API.*/  
  if (*s=='\0') {
    info ("[MySQL] empty '%s.password' entry in %s, assuming none", Section, cfg_source());
    strcpy(password,""); 
  }
  else strcpy(password,s);
  free(s);  
  
  s = cfg_get (Section, "database","\0");
  if (*s=='\0') {
    error ("[MySQL] no '%s:database' entry from %s, specify one", Section, cfg_source());
  }
  else {
    strcpy(database,s);
    free(s);  
    
    mysql_init(&conex);
    if (!mysql_real_connect(&conex,server,user,password,database,port,NULL,0))
      error( "[MySQL] conection error: %s",mysql_error(&conex));
    else
    {
      AddFunction ("MySQL::query",  1, my_MySQLquery);
      AddFunction ("MySQL::status", 0, my_MySQLstatus);
    }
  }
#endif
  return 0;
}

void plugin_exit_mysql(void) 
{
#ifdef HAVE_MYSQL_MYSQL_H
  mysql_close(&conex);
#endif
}
uot;cfg.h" /* struct timeval */ #include <sys/time.h> //source: http://www.musicpd.org/libmpdclient.shtml #include "libmpdclient.h" #ifdef WITH_DMALLOC #include <dmalloc.h> #endif #define TIMEOUT_IN_S 10 /* current song */ static int l_totalTimeSec; static int l_elapsedTimeSec; static int l_bitRate; static int l_repeatEnabled; static int l_randomEnabled; static int l_state; static int l_volume; static int l_numberOfSongs; static unsigned long l_uptime; static unsigned long l_playTime; static unsigned long l_dbPlayTime; static int l_playlistLength; /* pos in playlist */ static int l_currentSongPos; static unsigned int l_sampleRate; static int l_channels; static mpd_Song *currentSong; /* connection information */ static char host[255]; static char pw[255]; static int iport; static int plugin_enabled; static int waittime; struct timeval timestamp; static mpd_Connection * conn; static char Section[] = "Plugin:MPD"; static int configure_mpd(void) { static int configured = 0; char *s; if (configured != 0) return configured; /* read enabled */ if (cfg_number(Section, "enabled", 0, 0, 1, &plugin_enabled) < 1) { plugin_enabled = 0; } if (plugin_enabled != 1){ info("[MPD] WARNING: Plugin is not enabled! (set 'enabled 1' to enable this plugin)"); configured = 1; return configured; } /* read server */ s = cfg_get(Section, "server", "localhost"); if (*s == '\0') { info("[MPD] empty '%s.server' entry from %s, assuming 'localhost'", Section, cfg_source()); strcpy(host, "localhost"); } else strcpy(host, s); free(s); /* read port */ if (cfg_number(Section, "port", 6600, 1, 65536, &iport) < 1) { info("[MPD] no '%s.port' entry from %s using MPD's default", Section, cfg_source()); } /* read minUpdateTime in ms */ if (cfg_number(Section, "minUpdateTime", 500, 1, 10000, &waittime) < 1) { info("[MPD] no '%s.minUpdateTime' entry from %s using MPD's default", Section, cfg_source()); } /* read password */ s = cfg_get(Section, "password", ""); if (*s == '\0') { info("[MPD] empty '%s.password' entry in %s, assuming none", Section, cfg_source()); memset(pw, 0, sizeof(pw)); } else { strcpy(pw, s); free(s); } debug("[MPD] connection detail: [%s:%d]", host, iport); configured = 1; return configured; } static int mpd_update() { int ret = -1; struct timeval now; /* reread every 1000 msec only */ gettimeofday(&now, NULL); int timedelta = (now.tv_sec - timestamp.tv_sec) * 1000 + (now.tv_usec - timestamp.tv_usec) / 1000; if (timedelta < waittime) { //debug("[MPD] waittime not reached...\n"); return 1; } //check if configured if (configure_mpd() < 0) { return -1; } //check if connected if (conn==NULL || conn->error) { if (conn) { debug("[MPD] Error: [%s], try to reconnect to [%s]:[%i]\n", conn->errorStr, host, iport); mpd_closeConnection(conn); } else debug("[MPD] initialize connect to [%s]:[%i]\n", host, iport); conn = mpd_newConnection(host, iport, TIMEOUT_IN_S); if(conn->error) { error("[MPD] connection failed, give up..."); gettimeofday(&timestamp, NULL); return -1; } debug("[MPD] connection fixed..."); } mpd_Status * status=NULL; mpd_Stats *stats=NULL; mpd_InfoEntity * entity; mpd_sendCommandListOkBegin(conn); mpd_sendStatsCommand(conn); if(conn->error) { error("[MPD] error: %s", conn->errorStr); return -1; } mpd_sendStatusCommand(conn); mpd_sendCurrentSongCommand(conn); mpd_sendCommandListEnd(conn); //stats stats = mpd_getStats(conn); if(stats==NULL) { error("[MPD] error mpd_getStats: %s", conn->errorStr); goto cleanup; } //status mpd_nextListOkCommand(conn); if((status = mpd_getStatus(conn))==NULL) { error("[MPD] error mpd_nextListOkCommand: %s", conn->errorStr); goto cleanup; } //song mpd_nextListOkCommand(conn); while((entity = mpd_getNextInfoEntity(conn))) { mpd_Song * song = entity->info.song; if(entity->type!=MPD_INFO_ENTITY_TYPE_SONG) { mpd_freeInfoEntity(entity); continue; } if (currentSong!=NULL) mpd_freeSong(currentSong); currentSong = mpd_songDup(song); mpd_freeInfoEntity(entity); } l_elapsedTimeSec = status->elapsedTime; l_totalTimeSec = status->totalTime; l_repeatEnabled = status->repeat; l_randomEnabled = status->random; l_bitRate = status->bitRate; l_state = status->state; l_volume = status->volume; l_playlistLength = status->playlistLength; l_currentSongPos = status->song+1; l_sampleRate = status->sampleRate; l_channels = status->channels; l_numberOfSongs = stats->numberOfSongs; l_uptime = stats->uptime; l_playTime = stats->playTime; l_dbPlayTime = stats->dbPlayTime; /* sanity checks */ if (l_volume < 0 || l_volume > 100) l_volume = 0; if (l_bitRate < 0) l_bitRate = 0; if (l_elapsedTimeSec > l_totalTimeSec || l_elapsedTimeSec < 0) l_elapsedTimeSec = 0; ret = 0; cleanup: if (stats!=NULL) mpd_freeStats(stats); if (status!=NULL) mpd_freeStatus(status); if(conn->error) { error("[MPD] error: %s", conn->errorStr); return -1; } mpd_finishCommand(conn); if(conn->error) { error("[MPD] error mpd_finishCommand: %s", conn->errorStr); return -1; } gettimeofday(&timestamp, NULL); return ret; } static void elapsedTimeSec(RESULT * result) { double d; mpd_update(); d = (double)l_elapsedTimeSec; SetResult(&result, R_NUMBER, &d); } static void totalTimeSec(RESULT * result) { double d; mpd_update(); d = (double)l_totalTimeSec; SetResult(&result, R_NUMBER, &d); } static void bitRate(RESULT * result) { double d; mpd_update(); d = (double)l_bitRate; SetResult(&result, R_NUMBER, &d); } static void getRepeatInt(RESULT * result) { double d; mpd_update(); d = (double)l_repeatEnabled; SetResult(&result, R_NUMBER, &d); } static void getRandomInt(RESULT * result) { double d; mpd_update(); d = (double)l_randomEnabled; SetResult(&result, R_NUMBER, &d); } /* if no tag is availabe, use filename */ static void getArtist(RESULT * result) { mpd_update(); if (currentSong!=NULL) { if (currentSong->artist!=NULL) { SetResult(&result, R_STRING, currentSong->artist); } else { if (currentSong->file!=NULL) SetResult(&result, R_STRING, currentSong->file); else SetResult(&result, R_STRING, ""); } } else SetResult(&result, R_STRING, ""); } static void getTitle(RESULT * result) { mpd_update(); if (currentSong!=NULL) { if (currentSong->title!=NULL) { SetResult(&result, R_STRING, currentSong->title); } else SetResult(&result, R_STRING, ""); } else SetResult(&result, R_STRING, ""); } static void getAlbum(RESULT * result) { mpd_update(); if (currentSong!=NULL) { if (currentSong->album!=NULL) SetResult(&result, R_STRING, currentSong->album); else SetResult(&result, R_STRING, ""); } else SetResult(&result, R_STRING, ""); } static void getFilename(RESULT * result) { mpd_update(); if (currentSong!=NULL) { if (currentSong->file!=NULL) SetResult(&result, R_STRING, currentSong->file); else SetResult(&result, R_STRING, ""); } else SetResult(&result, R_STRING, ""); } /* return player state: 0=unknown 1=play 2=pause 3=stop */ static void getStateInt(RESULT * result) { double ret; mpd_update(); switch (l_state) { case MPD_STATUS_STATE_PLAY: ret = 1; break; case MPD_STATUS_STATE_PAUSE: ret = 2; break; case MPD_STATUS_STATE_STOP: ret = 3; break; default: ret = 0; break; } SetResult(&result, R_NUMBER, &ret); } static void getVolume(RESULT * result) { double d; mpd_update(); d = (double)l_volume; /* return 0..100 or < 0 when failed */ SetResult(&result, R_NUMBER, &d); } /* return the # of songs in the mpd db .. */ static void getSongsInDb(RESULT * result) { double d; mpd_update(); d = (double)l_numberOfSongs; SetResult(&result, R_NUMBER, &d); } static void getMpdUptime(RESULT * result) { double d; mpd_update(); d = (double)l_uptime; SetResult(&result, R_NUMBER, &d); } static void getMpdPlayTime(RESULT * result) { double d; mpd_update(); d = (double)l_playTime; SetResult(&result, R_NUMBER, &d); } static void getMpdDbPlayTime(RESULT * result) { double d; mpd_update(); d = (double)l_dbPlayTime; SetResult(&result, R_NUMBER, &d); } static void getMpdPlaylistLength(RESULT * result) { double d; mpd_update(); d = (double)l_playlistLength; SetResult(&result, R_NUMBER, &d); } static void getCurrentSongPos(RESULT * result) { double d; mpd_update(); d = (double)l_currentSongPos; SetResult(&result, R_NUMBER, &d); } static void getAudioChannels(RESULT * result) { double d; mpd_update(); d = (double)l_channels; SetResult(&result, R_NUMBER, &d); } static void getSamplerateHz(RESULT * result) { double d; mpd_update(); d = (double)l_sampleRate; SetResult(&result, R_NUMBER, &d); } static void formatTimeMMSS(RESULT * result, RESULT * param) { long sec; char myTime[6] = " "; sec = R2N(param); if ((sec >= 0) && (sec < 6000)) { const int minutes = (int) (sec / 60); const int seconds = (int) (sec % 60); sprintf(myTime, "%02d:%02d", minutes, seconds); } else if (sec >= 6000) { strcpy(myTime, "LONG"); } else strcpy(myTime, "ERROR"); /* store result */ SetResult(&result, R_STRING, myTime); } static void formatTimeDDHHMM(RESULT * result, RESULT * param) { long sec; char myTime[16] = " "; sec = R2N(param); if (sec >= 0) { int days = sec / 86400; int hours = (sec % 86400) / 3600; int minutes = (sec % 3600) / 60; sprintf(myTime, "%dd%02dh%02dm", days, hours, minutes); /* 3d 12:33h */ } else strcpy(myTime, "ERROR"); /* store result */ SetResult(&result, R_STRING, myTime); } int plugin_init_mpd(void) { int check; debug("[MPD] v0.81, check lcd4linux configuration file..."); check = configure_mpd(); if (plugin_enabled != 1) return 0; if (check) debug("[MPD] configured!"); else debug("[MPD] error, NOT configured!"); //when mpd dies, do NOT exit application, ignore it! signal(SIGPIPE, SIG_IGN); gettimeofday(&timestamp, NULL); AddFunction("mpd::artist", 0, getArtist); AddFunction("mpd::title", 0, getTitle); AddFunction("mpd::album", 0, getAlbum); AddFunction("mpd::file", 0, getFilename); AddFunction("mpd::totalTimeSec", 0, totalTimeSec); AddFunction("mpd::elapsedTimeSec", 0, elapsedTimeSec); AddFunction("mpd::bitRate", 0, bitRate); AddFunction("mpd::getSamplerateHz", 0, getSamplerateHz); AddFunction("mpd::getAudioChannels", 0, getAudioChannels); AddFunction("mpd::getRepeatInt", 0, getRepeatInt); AddFunction("mpd::getRandomInt", 0, getRandomInt); AddFunction("mpd::getStateInt", 0, getStateInt); AddFunction("mpd::getVolume", 0, getVolume); AddFunction("mpd::getSongsInDb", 0, getSongsInDb); AddFunction("mpd::getMpdUptime", 0, getMpdUptime); AddFunction("mpd::getMpdPlayTime", 0, getMpdPlayTime); AddFunction("mpd::getMpdDbPlayTime", 0, getMpdDbPlayTime); AddFunction("mpd::getMpdPlaylistLength", 0, getMpdPlaylistLength); AddFunction("mpd::getMpdPlaylistGetCurrentId", 0, getCurrentSongPos); AddFunction("mpd::formatTimeMMSS", 1, formatTimeMMSS); AddFunction("mpd::formatTimeDDHHMM", 1, formatTimeDDHHMM); return 0; } void plugin_exit_mpd(void) { if (plugin_enabled == 1){ debug("[MPD] disconnect from mpd"); if (currentSong!=NULL) mpd_freeSong(currentSong); mpd_closeConnection(conn); } }