The next generation of the Teknik Services. Written in ASP.NET.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Program.cs 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. using nClam;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data.Entity;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Mail;
  9. using System.Reflection;
  10. using System.Text;
  11. using Teknik.Areas.Status.Models;
  12. using Teknik.Areas.Upload.Models;
  13. using Teknik.Areas.Users.Models;
  14. using Teknik.Areas.Users.Utility;
  15. using Teknik.Configuration;
  16. using Teknik.Utilities;
  17. using Teknik.Models;
  18. using System.Threading.Tasks;
  19. namespace ServerMaint
  20. {
  21. public class Program
  22. {
  23. private static string currentPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
  24. private static string virusFile = Path.Combine(currentPath, "virusLogs.txt");
  25. private static string errorFile = Path.Combine(currentPath, "errorLogs.txt");
  26. private static string configPath = currentPath;
  27. private const string TAKEDOWN_REPORTER = "Teknik Automated System";
  28. private static readonly object dbLock = new object();
  29. private static readonly object scanStatsLock = new object();
  30. public static event Action<string> OutputEvent;
  31. public static int Main(string[] args)
  32. {
  33. try
  34. {
  35. ArgumentOptions options = new ArgumentOptions();
  36. var parser = new CommandLine.Parser(config => config.HelpWriter = Console.Out);
  37. if (parser.ParseArguments(args, options))
  38. {
  39. if (!string.IsNullOrEmpty(options.Config))
  40. configPath = options.Config;
  41. if (Directory.Exists(configPath))
  42. {
  43. Config config = Config.Load(configPath);
  44. TeknikEntities db = new TeknikEntities();
  45. Output(string.Format("[{0}] Started Server Maintenance Process.", DateTime.Now));
  46. // Scan all the uploads for viruses, and remove the bad ones
  47. if (options.ScanUploads && config.UploadConfig.VirusScanEnable)
  48. {
  49. ScanUploads(config, db);
  50. }
  51. // Warns all the invalid accounts via email
  52. if (options.WarnAccounts)
  53. {
  54. WarnInvalidAccounts(config, db);
  55. }
  56. // Cleans all inactive users
  57. if (options.CleanUsers)
  58. {
  59. CleanAccounts(config, db, options.DaysBeforeDeletion);
  60. }
  61. // Cleans the email for unused accounts
  62. if (options.CleanEmails)
  63. {
  64. CleanEmail(config, db);
  65. }
  66. // Cleans all the git accounts that are unused
  67. if (options.CleanGit)
  68. {
  69. CleanGit(config, db);
  70. }
  71. // Generates a file for all of the user's last seen dates
  72. if (options.GenerateLastSeen)
  73. {
  74. GenerateLastSeen(config, db, options.LastSeenFile);
  75. }
  76. // Generates a file for all of the invalid accounts
  77. if (options.GenerateInvalid)
  78. {
  79. GenerateInvalidAccounts(config, db, options.InvalidFile);
  80. }
  81. // Generates a file for all of the accounts to be cleaned
  82. if (options.GenerateCleaning)
  83. {
  84. GenerateCleaningList(config, db, options.CleaningFile, options.DaysBeforeDeletion);
  85. }
  86. Output(string.Format("[{0}] Finished Server Maintenance Process.", DateTime.Now));
  87. return 0;
  88. }
  89. else
  90. {
  91. string msg = string.Format("[{0}] Config File does not exist.", DateTime.Now);
  92. File.AppendAllLines(errorFile, new List<string> { msg });
  93. Output(msg);
  94. }
  95. }
  96. else
  97. {
  98. Output(options.GetUsage());
  99. }
  100. }
  101. catch (Exception ex)
  102. {
  103. string msg = string.Format("[{0}] Exception: {1}", DateTime.Now, ex.GetFullMessage(true));
  104. File.AppendAllLines(errorFile, new List<string> { msg });
  105. Output(msg);
  106. }
  107. return -1;
  108. }
  109. public static void ScanUploads(Config config, TeknikEntities db)
  110. {
  111. Output(string.Format("[{0}] Started Virus Scan.", DateTime.Now));
  112. List<Upload> uploads = db.Uploads.ToList();
  113. int totalCount = uploads.Count();
  114. int totalScans = 0;
  115. int totalViruses = 0;
  116. List<Task> runningTasks = new List<Task>();
  117. foreach (Upload upload in uploads)
  118. {
  119. int currentScan = totalScans++;
  120. Task scanTask = Task.Factory.StartNew(() => ScanUpload(config, db, upload, totalCount, currentScan, ref totalViruses));
  121. if (scanTask != null)
  122. {
  123. runningTasks.Add(scanTask);
  124. }
  125. }
  126. bool running = true;
  127. while (running)
  128. {
  129. running = runningTasks.Exists(s => s != null && !s.IsCompleted && !s.IsCanceled && !s.IsFaulted);
  130. }
  131. Output(string.Format("Scanning Complete. {0} Scanned | {1} Viruses Found | {2} Total Files", totalScans, totalViruses, totalCount));
  132. }
  133. private static void ScanUpload(Config config, TeknikEntities db, Upload upload, int totalCount, int currentCount, ref int totalViruses)
  134. {
  135. // Initialize ClamAV
  136. ClamClient clam = new ClamClient(config.UploadConfig.ClamServer, config.UploadConfig.ClamPort);
  137. clam.MaxStreamSize = config.UploadConfig.MaxUploadSize;
  138. string subDir = upload.FileName[0].ToString();
  139. string filePath = Path.Combine(config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  140. if (File.Exists(filePath))
  141. {
  142. // If the IV is set, and Key is set, then scan it
  143. if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  144. {
  145. byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
  146. byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
  147. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  148. AESCryptoStream aesStream = new AESCryptoStream(fs, false, keyBytes, ivBytes, "CTR", "NoPadding");
  149. // We have the data, let's scan it
  150. ClamScanResult scanResult = clam.SendAndScanFile(aesStream);
  151. // Close file stream
  152. fs.Close();
  153. switch (scanResult.Result)
  154. {
  155. case ClamScanResults.Clean:
  156. string cleanMsg = string.Format("[{0}] Clean Scan: {1}/{2} Scanned | {3} - {4}", DateTime.Now, currentCount, totalCount, upload.Url, upload.FileName);
  157. Output(cleanMsg);
  158. break;
  159. case ClamScanResults.VirusDetected:
  160. string msg = string.Format("[{0}] Virus Detected: {1} - {2} - {3}", DateTime.Now, upload.Url, upload.FileName, scanResult.InfectedFiles.First().VirusName);
  161. Output(msg);
  162. lock (scanStatsLock)
  163. {
  164. totalViruses++;
  165. File.AppendAllLines(virusFile, new List<string> { msg });
  166. }
  167. lock (dbLock)
  168. {
  169. string urlName = upload.Url;
  170. // Delete from the DB
  171. db.Uploads.Remove(upload);
  172. // Delete the File
  173. if (File.Exists(filePath))
  174. {
  175. File.Delete(filePath);
  176. }
  177. // Add to transparency report if any were found
  178. Takedown report = db.Takedowns.Create();
  179. report.Requester = TAKEDOWN_REPORTER;
  180. report.RequesterContact = config.SupportEmail;
  181. report.DateRequested = DateTime.Now;
  182. report.Reason = "Malware Found";
  183. report.ActionTaken = string.Format("Upload removed: {0}", urlName);
  184. report.DateActionTaken = DateTime.Now;
  185. db.Takedowns.Add(report);
  186. // Save Changes
  187. db.SaveChanges();
  188. }
  189. break;
  190. case ClamScanResults.Error:
  191. string errorMsg = string.Format("[{0}] Scan Error: {1}", DateTime.Now, scanResult.RawResult);
  192. File.AppendAllLines(errorFile, new List<string> { errorMsg });
  193. Output(errorMsg);
  194. break;
  195. case ClamScanResults.Unknown:
  196. string unkMsg = string.Format("[{0}] Unknown Scan Result: {1}", DateTime.Now, scanResult.RawResult);
  197. File.AppendAllLines(errorFile, new List<string> { unkMsg });
  198. Output(unkMsg);
  199. break;
  200. }
  201. }
  202. }
  203. }
  204. public static void WarnInvalidAccounts(Config config, TeknikEntities db)
  205. {
  206. Output(string.Format("[{0}] Started Warning of Invalid Accounts.", DateTime.Now));
  207. List<string> invalidAccounts = GetInvalidAccounts(config, db);
  208. foreach (string account in invalidAccounts)
  209. {
  210. // Let's send them an email :D
  211. string email = UserHelper.GetUserEmailAddress(config, account);
  212. SmtpClient client = new SmtpClient();
  213. client.Host = config.ContactConfig.EmailAccount.Host;
  214. client.Port = config.ContactConfig.EmailAccount.Port;
  215. client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
  216. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  217. client.UseDefaultCredentials = true;
  218. client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
  219. client.Timeout = 5000;
  220. try
  221. {
  222. MailMessage mail = new MailMessage(config.ContactConfig.EmailAccount.EmailAddress, email);
  223. mail.Subject = "Invalid Account Notice";
  224. mail.Body = string.Format(@"
  225. The account {0} does not meet the requirements for a valid username.
  226. The username must meet the following requirements: {1}
  227. It must also be greater than or equal to {2} characters in length, and less than or equal to {3} characters in length.
  228. This email is to let you know that this account will be deleted in {4} days ({5}) in order to comply with the username restrictions. If you would like to keep your data, you should create a new account and transfer the data over to the new account.
  229. In order to make the process as easy as possible, you can reply to this email to ask for your current account to be renamed to another available account. This would keep all your data intact, and just require you to change all references to your email/git/user to the new username. If you wish to do this, please respond within {6} days ({7}) with the new username you would like to use.
  230. Thank you for your continued use of Teknik!
  231. - Teknik Administration", account, config.UserConfig.UsernameFilterLabel, config.UserConfig.MinUsernameLength, config.UserConfig.MaxUsernameLength, 30, DateTime.Now.AddDays(30).ToShortDateString(), 15, DateTime.Now.AddDays(15).ToShortDateString());
  232. mail.BodyEncoding = UTF8Encoding.UTF8;
  233. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  234. client.Send(mail);
  235. }
  236. catch (Exception ex)
  237. {
  238. Output(string.Format("[{0}] Unable to send email to {1}. Exception: {2}", DateTime.Now, email, ex.Message));
  239. }
  240. }
  241. Output(string.Format("[{0}] Finished Warning of Invalid Accounts. {1} Accounts Warned.", DateTime.Now, invalidAccounts.Count));
  242. }
  243. public static void CleanAccounts(Config config, TeknikEntities db, int maxDays)
  244. {
  245. Output(string.Format("[{0}] Started Cleaning of Inactive/Invalid Users.", DateTime.Now));
  246. List<string> invalidAccounts = GetInvalidAccounts(config, db);
  247. List<string> inactiveAccounts = GetInactiveAccounts(config, db, maxDays);
  248. // Delete invalid accounts
  249. foreach (string account in invalidAccounts)
  250. {
  251. UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account));
  252. }
  253. if (invalidAccounts.Count > 0)
  254. {
  255. // Add to transparency report if any users were removed
  256. Takedown report = db.Takedowns.Create();
  257. report.Requester = TAKEDOWN_REPORTER;
  258. report.RequesterContact = config.SupportEmail;
  259. report.DateRequested = DateTime.Now;
  260. report.Reason = "Username Invalid";
  261. report.ActionTaken = string.Format("{0} Accounts Removed", invalidAccounts.Count);
  262. report.DateActionTaken = DateTime.Now;
  263. db.Takedowns.Add(report);
  264. db.SaveChanges();
  265. }
  266. // Delete inactive accounts
  267. foreach (string account in inactiveAccounts)
  268. {
  269. UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account));
  270. }
  271. if (invalidAccounts.Count > 0)
  272. {
  273. // Add to transparency report if any users were removed
  274. Takedown report = db.Takedowns.Create();
  275. report.Requester = TAKEDOWN_REPORTER;
  276. report.RequesterContact = config.SupportEmail;
  277. report.DateRequested = DateTime.Now;
  278. report.Reason = "Account Inactive";
  279. report.ActionTaken = string.Format("{0} Accounts Removed", inactiveAccounts.Count);
  280. report.DateActionTaken = DateTime.Now;
  281. db.Takedowns.Add(report);
  282. db.SaveChanges();
  283. }
  284. Output(string.Format("[{0}] Finished Cleaning of Inactive/Invalid Users. {1} Accounts Removed.", DateTime.Now, invalidAccounts.Count + inactiveAccounts.Count));
  285. }
  286. public static void CleanEmail(Config config, TeknikEntities db)
  287. {
  288. Output(string.Format("[{0}] Started Cleaning of Orphaned Email Accounts.", DateTime.Now));
  289. List<string> emails = GetOrphanedEmail(config, db);
  290. foreach (string email in emails)
  291. {
  292. // User doesn't exist, and it isn't reserved. Let's nuke it.
  293. UserHelper.DeleteUserEmail(config, email);
  294. }
  295. if (emails.Count > 0)
  296. {
  297. // Add to transparency report if any users were removed
  298. Takedown report = db.Takedowns.Create();
  299. report.Requester = TAKEDOWN_REPORTER;
  300. report.RequesterContact = config.SupportEmail;
  301. report.DateRequested = DateTime.Now;
  302. report.Reason = "Orphaned Email Account";
  303. report.ActionTaken = string.Format("{0} Accounts Removed", emails.Count);
  304. report.DateActionTaken = DateTime.Now;
  305. db.Takedowns.Add(report);
  306. db.SaveChanges();
  307. }
  308. Output(string.Format("[{0}] Finished Cleaning of Orphaned Email Accounts. {1} Accounts Removed.", DateTime.Now, emails.Count));
  309. }
  310. public static void CleanGit(Config config, TeknikEntities db)
  311. {
  312. Output(string.Format("[{0}] Started Cleaning of Orphaned Git Accounts.", DateTime.Now));
  313. List<string> gitAccounts = GetOrphanedGit(config, db);
  314. foreach (string account in gitAccounts)
  315. {
  316. // User doesn't exist, and it isn't reserved. Let's nuke it.
  317. UserHelper.DeleteUserGit(config, account);
  318. }
  319. if (gitAccounts.Count > 0)
  320. {
  321. // Add to transparency report if any users were removed
  322. Takedown report = db.Takedowns.Create();
  323. report.Requester = TAKEDOWN_REPORTER;
  324. report.RequesterContact = config.SupportEmail;
  325. report.DateRequested = DateTime.Now;
  326. report.Reason = "Orphaned Git Account";
  327. report.ActionTaken = string.Format("{0} Accounts Removed", gitAccounts.Count);
  328. report.DateActionTaken = DateTime.Now;
  329. db.Takedowns.Add(report);
  330. db.SaveChanges();
  331. }
  332. Output(string.Format("[{0}] Finished Cleaning of Orphaned Git Accounts. {1} Accounts Removed.", DateTime.Now, gitAccounts.Count));
  333. }
  334. public static void GenerateLastSeen(Config config, TeknikEntities db, string fileName)
  335. {
  336. Output(string.Format("[{0}] Started Generation of Last Activity List.", DateTime.Now));
  337. List<User> curUsers = db.Users.ToList();
  338. StringBuilder sb = new StringBuilder();
  339. sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
  340. foreach (User user in curUsers)
  341. {
  342. sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
  343. user.Username,
  344. UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
  345. user.JoinDate.ToString("g"),
  346. user.LastSeen.ToString("g"),
  347. UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
  348. UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
  349. }
  350. string dir = Path.GetDirectoryName(fileName);
  351. if (!Directory.Exists(dir))
  352. Directory.CreateDirectory(dir);
  353. File.WriteAllText(fileName, sb.ToString());
  354. Output(string.Format("[{0}] Finished Generating Last Activity List.", DateTime.Now));
  355. }
  356. public static void GenerateInvalidAccounts(Config config, TeknikEntities db, string fileName)
  357. {
  358. Output(string.Format("[{0}] Started Generation of Invalid Account List.", DateTime.Now));
  359. List<string> invalidAccounts = GetInvalidAccounts(config, db);
  360. StringBuilder sb = new StringBuilder();
  361. sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
  362. foreach (string account in invalidAccounts)
  363. {
  364. User user = UserHelper.GetUser(db, account);
  365. sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
  366. user.Username,
  367. UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
  368. user.JoinDate.ToString("g"),
  369. user.LastSeen.ToString("g"),
  370. UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
  371. UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
  372. }
  373. string dir = Path.GetDirectoryName(fileName);
  374. if (!Directory.Exists(dir))
  375. Directory.CreateDirectory(dir);
  376. File.WriteAllText(fileName, sb.ToString());
  377. Output(string.Format("[{0}] Finished Generating Invalid Account List.", DateTime.Now));
  378. }
  379. public static void GenerateCleaningList(Config config, TeknikEntities db, string fileName, int maxDays)
  380. {
  381. Output(string.Format("[{0}] Started Generation of Accounts to Clean List.", DateTime.Now));
  382. List<string> invalidAccounts = GetInvalidAccounts(config, db);
  383. List<string> inactiveAccounts = GetInactiveAccounts(config, db, maxDays);
  384. List<string> emailAccounts = GetOrphanedEmail(config, db);
  385. List<string> gitAccounts = GetOrphanedGit(config, db);
  386. StringBuilder sb = new StringBuilder();
  387. sb.AppendLine("Invalid Account Cleaning");
  388. sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
  389. foreach (string account in invalidAccounts)
  390. {
  391. User user = UserHelper.GetUser(db, account);
  392. sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
  393. user.Username,
  394. UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
  395. user.JoinDate.ToString("g"),
  396. user.LastSeen.ToString("g"),
  397. UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
  398. UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
  399. }
  400. sb.AppendLine();
  401. sb.AppendLine("Inactive Account Cleaning");
  402. sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
  403. foreach (string account in inactiveAccounts)
  404. {
  405. User user = UserHelper.GetUser(db, account);
  406. sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
  407. user.Username,
  408. UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
  409. user.JoinDate.ToString("g"),
  410. user.LastSeen.ToString("g"),
  411. UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
  412. UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
  413. }
  414. sb.AppendLine();
  415. sb.AppendLine("Orphaned Email Cleaning");
  416. sb.AppendLine("Email,Last Activity");
  417. foreach (string account in emailAccounts)
  418. {
  419. sb.AppendLine(string.Format("{0},{1}",
  420. account,
  421. UserHelper.UserEmailLastActive(config, account).ToString("g")));
  422. }
  423. sb.AppendLine();
  424. sb.AppendLine("Orphaned Git Cleaning");
  425. sb.AppendLine("Username,Last Activity");
  426. foreach (string account in gitAccounts)
  427. {
  428. sb.AppendLine(string.Format("{0},{1}",
  429. account,
  430. UserHelper.UserGitLastActive(config, account).ToString("g")));
  431. }
  432. string dir = Path.GetDirectoryName(fileName);
  433. if (!Directory.Exists(dir))
  434. Directory.CreateDirectory(dir);
  435. File.WriteAllText(fileName, sb.ToString());
  436. Output(string.Format("[{0}] Finished Generating Accounts to Clean List.", DateTime.Now));
  437. }
  438. public static List<string> GetInvalidAccounts(Config config, TeknikEntities db)
  439. {
  440. List<string> foundUsers = new List<string>();
  441. List<User> curUsers = db.Users.ToList();
  442. foreach (User user in curUsers)
  443. {
  444. // If the username is reserved, let's add it to the list
  445. if (UserHelper.UsernameReserved(config, user.Username))
  446. {
  447. foundUsers.Add(user.Username);
  448. continue;
  449. }
  450. // If the username is invalid, let's add it to the list
  451. if (!UserHelper.ValidUsername(config, user.Username) && user.Username != "Server Admin")
  452. {
  453. foundUsers.Add(user.Username);
  454. continue;
  455. }
  456. }
  457. return foundUsers;
  458. }
  459. public static List<string> GetInactiveAccounts(Config config, TeknikEntities db, int maxDays)
  460. {
  461. List<string> foundUsers = new List<string>();
  462. List<User> curUsers = db.Users.ToList();
  463. foreach (User user in curUsers)
  464. {
  465. // If the username is reserved, don't worry about it
  466. if (UserHelper.UsernameReserved(config, user.Username))
  467. {
  468. continue;
  469. }
  470. #region Inactivity Finding
  471. DateTime lastActivity = UserHelper.GetLastAccountActivity(db, config, user);
  472. TimeSpan inactiveTime = DateTime.Now.Subtract(lastActivity);
  473. // If older than max days, check their current usage
  474. if (inactiveTime >= new TimeSpan(maxDays, 0, 0, 0, 0))
  475. {
  476. // Check the user's usage of the service.
  477. bool noData = true;
  478. // Any blog comments?
  479. var blogCom = db.BlogComments.Where(c => c.UserId == user.UserId);
  480. noData &= !(blogCom != null && blogCom.Any());
  481. // Any blog posts?
  482. var blogPosts = db.BlogPosts.Where(p => p.Blog.UserId == user.UserId);
  483. noData &= !(blogPosts != null && blogPosts.Any());
  484. // Any podcast comments?
  485. var podCom = db.PodcastComments.Where(p => p.UserId == user.UserId);
  486. noData &= !(podCom != null && podCom.Any());
  487. // Any email?
  488. if (config.EmailConfig.Enabled)
  489. {
  490. var app = new hMailServer.Application();
  491. app.Connect();
  492. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  493. try
  494. {
  495. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  496. var account = domain.Accounts.ItemByAddress[UserHelper.GetUserEmailAddress(config, user.Username)];
  497. noData &= ((account.Messages.Count == 0) && ((int)account.Size == 0));
  498. }
  499. catch { }
  500. }
  501. // Any git repos?
  502. if (config.GitConfig.Enabled)
  503. {
  504. string email = UserHelper.GetUserEmailAddress(config, user.Username);
  505. // We need to check the actual git database
  506. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  507. string sql = @"SELECT * FROM gogs.repository
  508. LEFT JOIN gogs.action ON gogs.user.id = gogs.action.act_user_id
  509. WHERE gogs.user.login_name = {0}";
  510. var results = mySQL.Query(sql, new object[] { email });
  511. noData &= !(results != null && results.Any());
  512. }
  513. if (noData)
  514. {
  515. // They have no data, so safe to delete them.
  516. foundUsers.Add(user.Username);
  517. }
  518. continue;
  519. }
  520. #endregion
  521. }
  522. return foundUsers;
  523. }
  524. public static List<string> GetOrphanedEmail(Config config, TeknikEntities db)
  525. {
  526. List<string> foundEmail = new List<string>();
  527. if (config.EmailConfig.Enabled)
  528. {
  529. List<User> curUsers = db.Users.ToList();
  530. // Connect to hmailserver COM
  531. var app = new hMailServer.Application();
  532. app.Connect();
  533. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  534. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  535. var accounts = domain.Accounts;
  536. for (int i = 0; i < accounts.Count; i++)
  537. {
  538. var account = accounts[i];
  539. bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username) == account.Address);
  540. bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r).ToLower() == account.Address.ToLower());
  541. if (!userExists && !isReserved)
  542. {
  543. foundEmail.Add(account.Address);
  544. }
  545. }
  546. }
  547. return foundEmail;
  548. }
  549. public static List<string> GetOrphanedGit(Config config, TeknikEntities db)
  550. {
  551. List<string> foundGit = new List<string>();
  552. if (config.GitConfig.Enabled)
  553. {
  554. List<User> curUsers = db.Users.ToList();
  555. // We need to check the actual git database
  556. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  557. string sql = @"SELECT gogs.user.login_name AS login_name, gogs.user.lower_name AS username FROM gogs.user";
  558. var results = mySQL.Query(sql);
  559. if (results != null && results.Any())
  560. {
  561. foreach (var account in results)
  562. {
  563. bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username).ToLower() == account["login_name"].ToString().ToLower());
  564. bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r) == account["login_name"].ToString().ToLower());
  565. if (!userExists && !isReserved)
  566. {
  567. foundGit.Add(account["username"].ToString());
  568. }
  569. }
  570. }
  571. }
  572. return foundGit;
  573. }
  574. public static void Output(string message)
  575. {
  576. Console.WriteLine(message);
  577. if (OutputEvent != null)
  578. {
  579. OutputEvent(message);
  580. }
  581. }
  582. }
  583. }