[addondb] adds CAddonDatabase::GetAddonVersion() to speed up repository parsing
[vuplus_xbmc] / xbmc / addons / Repository.cpp
1 /*
2  *      Copyright (C) 2005-2013 Team XBMC
3  *      http://xbmc.org
4  *
5  *  This Program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2, or (at your option)
8  *  any later version.
9  *
10  *  This Program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with XBMC; see the file COPYING.  If not, see
17  *  <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 #include "Repository.h"
22 #include "addons/AddonDatabase.h"
23 #include "addons/AddonInstaller.h"
24 #include "addons/AddonManager.h"
25 #include "dialogs/GUIDialogYesNo.h"
26 #include "dialogs/GUIDialogKaiToast.h"
27 #include "filesystem/File.h"
28 #include "filesystem/PluginDirectory.h"
29 #include "pvr/PVRManager.h"
30 #include "settings/Settings.h"
31 #include "utils/log.h"
32 #include "utils/StringUtils.h"
33 #include "utils/URIUtils.h"
34 #include "utils/XBMCTinyXML.h"
35 #include "FileItem.h"
36 #include "TextureDatabase.h"
37 #include "URL.h"
38
39 using namespace std;
40 using namespace XFILE;
41 using namespace ADDON;
42
43 AddonPtr CRepository::Clone() const
44 {
45   return AddonPtr(new CRepository(*this));
46 }
47
48 CRepository::CRepository(const AddonProps& props) :
49   CAddon(props)
50 {
51 }
52
53 CRepository::CRepository(const cp_extension_t *ext)
54   : CAddon(ext)
55 {
56   // read in the other props that we need
57   if (ext)
58   {
59     AddonVersion version("0.0.0");
60     AddonPtr addonver;
61     if (CAddonMgr::Get().GetAddon("xbmc.addon", addonver))
62       version = addonver->Version();
63     for (size_t i = 0; i < ext->configuration->num_children; ++i)
64     {
65       if(ext->configuration->children[i].name &&
66          strcmp(ext->configuration->children[i].name, "dir") == 0)
67       {
68         AddonVersion min_version(CAddonMgr::Get().GetExtValue(&ext->configuration->children[i], "@minversion"));
69         if (min_version <= version)
70         {
71           DirInfo dir;
72           dir.version    = min_version;
73           dir.checksum   = CAddonMgr::Get().GetExtValue(&ext->configuration->children[i], "checksum");
74           dir.compressed = CAddonMgr::Get().GetExtValue(&ext->configuration->children[i], "info@compressed").Equals("true");
75           dir.info       = CAddonMgr::Get().GetExtValue(&ext->configuration->children[i], "info");
76           dir.datadir    = CAddonMgr::Get().GetExtValue(&ext->configuration->children[i], "datadir");
77           dir.zipped     = CAddonMgr::Get().GetExtValue(&ext->configuration->children[i], "datadir@zip").Equals("true");
78           dir.hashes     = CAddonMgr::Get().GetExtValue(&ext->configuration->children[i], "hashes").Equals("true");
79           m_dirs.push_back(dir);
80         }
81       }
82     }
83     // backward compatibility
84     if (!CAddonMgr::Get().GetExtValue(ext->configuration, "info").empty())
85     {
86       DirInfo info;
87       info.checksum   = CAddonMgr::Get().GetExtValue(ext->configuration, "checksum");
88       info.compressed = CAddonMgr::Get().GetExtValue(ext->configuration, "info@compressed").Equals("true");
89       info.info       = CAddonMgr::Get().GetExtValue(ext->configuration, "info");
90       info.datadir    = CAddonMgr::Get().GetExtValue(ext->configuration, "datadir");
91       info.zipped     = CAddonMgr::Get().GetExtValue(ext->configuration, "datadir@zip").Equals("true");
92       info.hashes     = CAddonMgr::Get().GetExtValue(ext->configuration, "hashes").Equals("true");
93       m_dirs.push_back(info);
94     }
95   }
96 }
97
98 CRepository::CRepository(const CRepository &rhs)
99   : CAddon(rhs)
100 {
101   m_dirs = rhs.m_dirs;
102 }
103
104 CRepository::~CRepository()
105 {
106 }
107
108 string CRepository::Checksum() const
109 {
110   string result;
111   for (DirList::const_iterator it  = m_dirs.begin(); it != m_dirs.end(); ++it)
112   {
113     if (!it->checksum.empty())
114       result += FetchChecksum(it->checksum);
115   }
116   return result;
117 }
118
119 string CRepository::FetchChecksum(const string& url)
120 {
121   CFile file;
122   try
123   {
124     if (file.Open(url))
125     {    
126       // we intentionally avoid using file.GetLength() for 
127       // Transfer-Encoding: chunked servers.
128       std::stringstream str;
129       char temp[1024];
130       int read;
131       while ((read=file.Read(temp, sizeof(temp))) > 0)
132         str.write(temp, read);
133       return str.str();
134     }
135     return "";
136   }
137   catch (...)
138   {
139     return "";
140   }
141 }
142
143 string CRepository::GetAddonHash(const AddonPtr& addon) const
144 {
145   string checksum;
146   DirList::const_iterator it;
147   for (it = m_dirs.begin();it != m_dirs.end(); ++it)
148     if (URIUtils::IsInPath(addon->Path(), it->datadir))
149       break;
150   if (it != m_dirs.end() && it->hashes)
151   {
152     checksum = FetchChecksum(addon->Path()+".md5");
153     size_t pos = checksum.find_first_of(" \n");
154     if (pos != string::npos)
155       return checksum.substr(0, pos);
156   }
157   return checksum;
158 }
159
160 #define SET_IF_NOT_EMPTY(x,y) \
161   { \
162     if (!x.empty()) \
163        x = y; \
164   }
165
166 VECADDONS CRepository::Parse(const DirInfo& dir)
167 {
168   VECADDONS result;
169   CXBMCTinyXML doc;
170
171   string file = dir.info;
172   if (dir.compressed)
173   {
174     CURL url(dir.info);
175     string opts = url.GetProtocolOptions();
176     if (!opts.empty())
177       opts += "&";
178     url.SetProtocolOptions(opts+"Encoding=gzip");
179     file = url.Get();
180   }
181
182   if (doc.LoadFile(file) && doc.RootElement())
183   {
184     CAddonMgr::Get().AddonsFromRepoXML(doc.RootElement(), result);
185     for (IVECADDONS i = result.begin(); i != result.end(); ++i)
186     {
187       AddonPtr addon = *i;
188       if (dir.zipped)
189       {
190         string file = StringUtils::Format("%s/%s-%s.zip", addon->ID().c_str(), addon->ID().c_str(), addon->Version().c_str());
191         addon->Props().path = URIUtils::AddFileToFolder(dir.datadir,file);
192         SET_IF_NOT_EMPTY(addon->Props().icon,URIUtils::AddFileToFolder(dir.datadir,addon->ID()+"/icon.png"))
193         file = StringUtils::Format("%s/changelog-%s.txt", addon->ID().c_str(), addon->Version().c_str());
194         SET_IF_NOT_EMPTY(addon->Props().changelog,URIUtils::AddFileToFolder(dir.datadir,file))
195         SET_IF_NOT_EMPTY(addon->Props().fanart,URIUtils::AddFileToFolder(dir.datadir,addon->ID()+"/fanart.jpg"))
196       }
197       else
198       {
199         addon->Props().path = URIUtils::AddFileToFolder(dir.datadir,addon->ID()+"/");
200         SET_IF_NOT_EMPTY(addon->Props().icon,URIUtils::AddFileToFolder(dir.datadir,addon->ID()+"/icon.png"))
201         SET_IF_NOT_EMPTY(addon->Props().changelog,URIUtils::AddFileToFolder(dir.datadir,addon->ID()+"/changelog.txt"))
202         SET_IF_NOT_EMPTY(addon->Props().fanart,URIUtils::AddFileToFolder(dir.datadir,addon->ID()+"/fanart.jpg"))
203       }
204     }
205   }
206
207   return result;
208 }
209
210 CRepositoryUpdateJob::CRepositoryUpdateJob(const VECADDONS &repos)
211   : m_repos(repos)
212 {
213 }
214
215 void MergeAddons(map<string, AddonPtr> &addons, const VECADDONS &new_addons)
216 {
217   for (VECADDONS::const_iterator it = new_addons.begin(); it != new_addons.end(); ++it)
218   {
219     map<string, AddonPtr>::iterator existing = addons.find((*it)->ID());
220     if (existing != addons.end())
221     { // already got it - replace if we have a newer version
222       if (existing->second->Version() < (*it)->Version())
223         existing->second = *it;
224     }
225     else
226       addons.insert(make_pair((*it)->ID(), *it));
227   }
228 }
229
230 bool CRepositoryUpdateJob::DoWork()
231 {
232   map<string, AddonPtr> addons;
233   for (VECADDONS::const_iterator i = m_repos.begin(); i != m_repos.end(); ++i)
234   {
235     RepositoryPtr repo = boost::dynamic_pointer_cast<CRepository>(*i);
236     VECADDONS newAddons = GrabAddons(repo);
237     MergeAddons(addons, newAddons);
238   }
239   if (addons.empty())
240     return false;
241
242   // check for updates
243   CAddonDatabase database;
244   database.Open();
245   database.BeginMultipleExecute();
246
247   CTextureDatabase textureDB;
248   textureDB.Open();
249   for (map<string, AddonPtr>::const_iterator i = addons.begin(); i != addons.end(); ++i)
250   {
251     // manager told us to feck off
252     if (ShouldCancel(0,0))
253       break;
254
255     AddonPtr newAddon = i->second;
256     bool deps_met = CAddonInstaller::Get().CheckDependencies(newAddon, &database);
257     if (!deps_met && newAddon->Props().broken.empty())
258       newAddon->Props().broken = "DEPSNOTMET";
259
260     // invalidate the art associated with this item
261     if (!newAddon->Props().fanart.empty())
262       textureDB.InvalidateCachedTexture(newAddon->Props().fanart);
263     if (!newAddon->Props().icon.empty())
264       textureDB.InvalidateCachedTexture(newAddon->Props().icon);
265
266     AddonPtr addon;
267     CAddonMgr::Get().GetAddon(newAddon->ID(),addon);
268     if (addon && newAddon->Version() > addon->Version() &&
269         !database.IsAddonBlacklisted(newAddon->ID(),newAddon->Version().c_str()) &&
270         deps_met)
271     {
272       if (CSettings::Get().GetBool("general.addonautoupdate") || addon->Type() >= ADDON_VIZ_LIBRARY)
273       {
274         string referer;
275         if (URIUtils::IsInternetStream(newAddon->Path()))
276           referer = StringUtils::Format("Referer=%s-%s.zip",addon->ID().c_str(),addon->Version().c_str());
277
278         if (newAddon->Type() == ADDON_PVRDLL &&
279             !PVR::CPVRManager::Get().InstallAddonAllowed(newAddon->ID()))
280           PVR::CPVRManager::Get().MarkAsOutdated(addon->ID(), referer);
281         else
282           CAddonInstaller::Get().Install(addon->ID(), true, referer);
283       }
284       else if (CSettings::Get().GetBool("general.addonnotifications"))
285       {
286         CGUIDialogKaiToast::QueueNotification(addon->Icon(),
287                                               g_localizeStrings.Get(24061),
288                                               addon->Name(),TOAST_DISPLAY_TIME,false,TOAST_DISPLAY_TIME);
289       }
290     }
291
292     // Check if we should mark the add-on as broken.  We may have a newer version
293     // of this add-on in the database or installed - if so, we keep it unbroken.
294     bool haveNewer = (addon && addon->Version() > newAddon->Version()) ||
295                      database.GetAddonVersion(newAddon->ID()) > newAddon->Version();
296     if (!haveNewer)
297     {
298       if (!newAddon->Props().broken.empty())
299       {
300         if (database.IsAddonBroken(newAddon->ID()).empty())
301         {
302           std::string line = g_localizeStrings.Get(24096);
303           if (newAddon->Props().broken == "DEPSNOTMET")
304             line = g_localizeStrings.Get(24104);
305           if (addon && CGUIDialogYesNo::ShowAndGetInput(newAddon->Name(),
306                                                line,
307                                                g_localizeStrings.Get(24097),
308                                                ""))
309             CAddonMgr::Get().DisableAddon(newAddon->ID());
310         }
311       }
312       database.BreakAddon(newAddon->ID(), newAddon->Props().broken);
313     }
314   }
315   database.CommitMultipleExecute();
316
317   return true;
318 }
319
320 VECADDONS CRepositoryUpdateJob::GrabAddons(RepositoryPtr& repo)
321 {
322   CAddonDatabase database;
323   database.Open();
324   string checksum;
325   database.GetRepoChecksum(repo->ID(),checksum);
326   string reposum = repo->Checksum();
327   VECADDONS addons;
328   if (checksum != reposum || checksum.empty())
329   {
330     map<string, AddonPtr> uniqueAddons;
331     for (CRepository::DirList::const_iterator it = repo->m_dirs.begin(); it != repo->m_dirs.end(); ++it)
332     {
333       VECADDONS addons2 = CRepository::Parse(*it);
334       MergeAddons(uniqueAddons, addons2);
335     }
336
337     if (uniqueAddons.empty())
338     {
339       CLog::Log(LOGERROR,"Repository %s returned no add-ons, listing may have failed",repo->Name().c_str());
340       reposum = checksum; // don't update the checksum
341     }
342     else
343     {
344       bool add=true;
345       if (!repo->Props().libname.empty())
346       {
347         CFileItemList dummy;
348         string s = StringUtils::Format("plugin://%s/?action=update", repo->ID().c_str());
349         add = CDirectory::GetDirectory(s, dummy);
350       }
351       if (add)
352       {
353         for (map<string, AddonPtr>::const_iterator i = uniqueAddons.begin(); i != uniqueAddons.end(); ++i)
354           addons.push_back(i->second);
355         database.AddRepository(repo->ID(),addons,reposum);
356       }
357     }
358   }
359   else
360     database.GetRepository(repo->ID(),addons);
361   database.SetRepoTimestamp(repo->ID(),CDateTime::GetCurrentDateTime().GetAsDBDateTime());
362
363   return addons;
364 }
365