CCMain.m 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "JDStatusBarNotification.h"
  35. #import "NCAutoUpload.h"
  36. #import "NCClientEncryption.h"
  37. #import "NCBridgeSwift.h"
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  39. {
  40. tableMetadata *_metadata;
  41. BOOL _isRoot;
  42. BOOL _isViewDidLoad;
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. NSMutableDictionary *_statusSwipeCell;
  48. UIImageView *_ImageTitleHomeCryptoCloud;
  49. UIView *_reMenuBackgroundView;
  50. UITapGestureRecognizer *_singleFingerTap;
  51. NSString *_directoryGroupBy;
  52. NSString *_directoryOrder;
  53. NSUInteger _failedAttempts;
  54. NSDate *_lockUntilDate;
  55. NSString *_fatherPermission;
  56. UIRefreshControl *_refreshControl;
  57. UIDocumentInteractionController *_docController;
  58. CCHud *_hud;
  59. CCHud *_hudDeterminate;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. BOOL _loadingFolder;
  74. }
  75. @end
  76. @implementation CCMain
  77. #pragma --------------------------------------------------------------------------------------------
  78. #pragma mark ===== Init =====
  79. #pragma --------------------------------------------------------------------------------------------
  80. - (id)initWithCoder:(NSCoder *)aDecoder
  81. {
  82. if (self = [super initWithCoder:aDecoder]) {
  83. _directoryOrder = [CCUtility getOrderSettings];
  84. _directoryGroupBy = [CCUtility getGroupBySettings];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  90. }
  91. return self;
  92. }
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== View =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. // init object
  100. _metadata = [tableMetadata new];
  101. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  104. _statusSwipeCell = [NSMutableDictionary new];
  105. _queueSelector = [NSMutableArray new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _noFilesSearchTitle = @"";
  112. _noFilesSearchDescription = @"";
  113. // delegate
  114. self.tableView.delegate = self;
  115. self.tableView.tableFooterView = [UIView new];
  116. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  117. self.tableView.emptyDataSetDelegate = self;
  118. self.tableView.emptyDataSetSource = self;
  119. self.searchController.delegate = self;
  120. self.searchController.searchBar.delegate = self;
  121. [CCNetworking sharedNetworking].delegate = self;
  122. // Custom Cell
  123. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  125. // long press recognizer TableView
  126. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  127. [self.tableView addGestureRecognizer:longPressRecognizer];
  128. // Pull-to-Refresh
  129. [self createRefreshControl];
  130. // Register for 3D Touch Previewing if available
  131. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  132. {
  133. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  134. }
  135. // Back Button
  136. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  137. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  138. // reMenu Background
  139. _reMenuBackgroundView = [[UIView alloc] init];
  140. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  141. // if this is not Main (the Main uses inizializeMain)
  142. if (_isRoot == NO && app.activeAccount.length > 0) {
  143. // Settings this folder & delegate & Loading datasource
  144. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  145. // Load Datasource
  146. [self reloadDatasource:_serverUrl];
  147. // Read (File) Folder
  148. [self readFileReloadFolder];
  149. }
  150. // Title
  151. [self setTitle];
  152. // Search
  153. self.definesPresentationContext = YES;
  154. self.searchController.searchResultsUpdater = self;
  155. self.searchController.dimsBackgroundDuringPresentation = NO;
  156. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  157. [self.searchController.searchBar sizeToFit];
  158. self.searchController.searchBar.delegate = self;
  159. if (@available(iOS 11, *)) {
  160. self.navigationItem.searchController = self.searchController;
  161. self.navigationItem.hidesSearchBarWhenScrolling = true;
  162. self.navigationItem.searchController.searchBar.tintColor = [UIColor whiteColor];
  163. UITextField *textField = [self.searchController.searchBar valueForKey:@"searchField"];
  164. textField.textColor = [UIColor blackColor];
  165. textField.tintColor = [UIColor blackColor];
  166. UIView *backgroundView = textField.subviews.firstObject;
  167. backgroundView.backgroundColor = UIColor.whiteColor;
  168. backgroundView.layer.cornerRadius = 10;
  169. backgroundView.clipsToBounds = YES;
  170. } else {
  171. self.tableView.tableHeaderView = self.searchController.searchBar;
  172. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  173. }
  174. }
  175. // Apparirà
  176. - (void)viewWillAppear:(BOOL)animated
  177. {
  178. [super viewWillAppear:animated];
  179. // test
  180. if (app.activeAccount.length == 0)
  181. return;
  182. // Settings this folder & delegate & Loading datasource
  183. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  184. [CCNetworking sharedNetworking].delegate = self;
  185. // Color
  186. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  187. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  188. if (_isSelectedMode)
  189. [self setUINavigationBarSelected];
  190. else
  191. [self setUINavigationBarDefault];
  192. // If not editing mode remove _selectedFileIDs
  193. if (!self.tableView.editing)
  194. [_selectedFileIDsMetadatas removeAllObjects];
  195. // Plus Button
  196. [app plusButtonVisibile:true];
  197. }
  198. // E' arrivato
  199. - (void)viewDidAppear:(BOOL)animated
  200. {
  201. [super viewDidAppear:animated];
  202. // Active Main
  203. app.activeMain = self;
  204. // Test viewDidLoad
  205. if (_isViewDidLoad) {
  206. _isViewDidLoad = NO;
  207. } else {
  208. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  209. // Load Datasource
  210. [self reloadDatasource:_serverUrl];
  211. // Read (file) Folder
  212. [self readFileReloadFolder];
  213. }
  214. }
  215. // Title
  216. [self setTitle];
  217. }
  218. - (void)viewWillDisappear:(BOOL)animated
  219. {
  220. [super viewWillDisappear:animated];
  221. [self closeAllMenu];
  222. }
  223. - (void)didReceiveMemoryWarning
  224. {
  225. [super didReceiveMemoryWarning];
  226. // Dispose of any resources that can be recreated.
  227. }
  228. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  229. {
  230. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  231. [self closeAllMenu];
  232. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  233. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  234. // Portrait
  235. } else {
  236. // Landscape
  237. }
  238. [self.tableView reloadData];
  239. }];
  240. }
  241. - (BOOL)prefersStatusBarHidden
  242. {
  243. return NO;
  244. }
  245. // detect scroll for remove keyboard in search mode
  246. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  247. {
  248. if (_isSearchMode && scrollView == self.tableView) {
  249. [self.searchController.searchBar endEditing:YES];
  250. }
  251. }
  252. - (void)changeTheming
  253. {
  254. if (self.isViewLoaded && self.view.window)
  255. [app changeTheming:self];
  256. // Refresh control
  257. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  258. // Reload Table View
  259. [self tableViewReloadData];
  260. }
  261. #pragma --------------------------------------------------------------------------------------------
  262. #pragma mark ===== Initizlize Mail =====
  263. #pragma --------------------------------------------------------------------------------------------
  264. - (void)initializeMain:(NSNotification *)notification
  265. {
  266. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  267. _directoryGroupBy = nil;
  268. _directoryOrder = nil;
  269. _dateReadDataSource = nil;
  270. // test
  271. if (app.activeAccount.length == 0)
  272. return;
  273. if ([app.listMainVC count] == 0 || _isRoot) {
  274. // This is Root home main add list
  275. appDelegate.homeMain = self;
  276. _isRoot = YES;
  277. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  278. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  279. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  280. // go Home
  281. [self.navigationController popToRootViewControllerAnimated:NO];
  282. // setting Networking
  283. [CCNetworking sharedNetworking].delegate = self;
  284. [[CCNetworking sharedNetworking] settingAccount];
  285. // Remove search mode
  286. [self cancelSearchBar];
  287. // populate shared Link & User
  288. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  289. if (results) {
  290. appDelegate.sharesLink = results[0];
  291. appDelegate.sharesUserAndGroup = results[1];
  292. }
  293. // Load Datasource
  294. [self reloadDatasource:_serverUrl];
  295. // Read (File) Folder
  296. [self readFileReloadFolder];
  297. // Setting Theming
  298. [app settingThemingColorBrand];
  299. // Load photo datasorce
  300. if (appDelegate.activePhotos)
  301. [appDelegate.activePhotos reloadDatasourceForced];
  302. // remove all of detail
  303. if (appDelegate.activeDetail)
  304. [appDelegate.activeDetail removeAllView];
  305. // remove all Notification Messages
  306. [appDelegate.listOfNotifications removeAllObjects];
  307. // Not Photos Video in library ? then align
  308. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", app.activeAccount]];
  309. if ([recordsPhotoLibrary count] == 0) {
  310. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  311. }
  312. // Initializations
  313. [appDelegate applicationInitialized];
  314. } else {
  315. // reload datasource
  316. [self reloadDatasource:_serverUrl];
  317. }
  318. }
  319. #pragma --------------------------------------------------------------------------------------------
  320. #pragma mark ==== DZNEmptyDataSetSource ====
  321. #pragma --------------------------------------------------------------------------------------------
  322. - (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
  323. {
  324. CGFloat safeAreaTop = 0;
  325. CGFloat safeAreaBottom = 0;
  326. if (@available(iOS 11, *)) {
  327. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  328. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  329. }
  330. //CGFloat searchBar = self.searchController.searchBar.frame.size.height;
  331. CGFloat tabBar = self.tabBarController.tabBar.frame.size.height;
  332. return - (tabBar + safeAreaBottom);
  333. }
  334. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  335. {
  336. if (_loadingFolder)
  337. return NO;
  338. else
  339. return YES;
  340. }
  341. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  342. {
  343. return [UIColor whiteColor];
  344. }
  345. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  346. {
  347. if (_isSearchMode)
  348. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  349. else
  350. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  351. }
  352. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  353. {
  354. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  355. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  356. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  357. activityView.color = [NCBrandColor sharedInstance].brand;
  358. [activityView startAnimating];
  359. return activityView;
  360. }
  361. return nil;
  362. }
  363. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  364. {
  365. NSString *text;
  366. if (_isSearchMode) {
  367. text = _noFilesSearchTitle;
  368. } else {
  369. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  370. }
  371. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  372. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  373. }
  374. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  375. {
  376. NSString *text;
  377. if (_isSearchMode) {
  378. text = _noFilesSearchDescription;
  379. } else {
  380. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  381. }
  382. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  383. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  384. paragraph.alignment = NSTextAlignmentCenter;
  385. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  386. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  387. }
  388. #pragma --------------------------------------------------------------------------------------------
  389. #pragma mark ===== Text Field =====
  390. #pragma --------------------------------------------------------------------------------------------
  391. - (void)minCharTextFieldDidChange:(UITextField *)sender
  392. {
  393. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  394. if (alertController)
  395. {
  396. UITextField *fileName = alertController.textFields.firstObject;
  397. UIAlertAction *okAction = alertController.actions.lastObject;
  398. okAction.enabled = fileName.text.length > 0;
  399. }
  400. }
  401. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  402. [textField selectAll:textField];
  403. }
  404. #pragma --------------------------------------------------------------------------------------------
  405. #pragma mark ===== Graphic Window =====
  406. #pragma --------------------------------------------------------------------------------------------
  407. - (void)createRefreshControl
  408. {
  409. _refreshControl = [UIRefreshControl new];
  410. if (@available(iOS 11.0, *)) {
  411. [self.tableView setRefreshControl:_refreshControl];
  412. _refreshControl.tintColor = [UIColor whiteColor];
  413. } else {
  414. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  415. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  416. [self setRefreshControl:_refreshControl];
  417. }
  418. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  419. }
  420. - (void)deleteRefreshControl
  421. {
  422. [_refreshControl endRefreshing];
  423. self.refreshControl = nil;
  424. }
  425. - (void)refreshControlTarget
  426. {
  427. [self readFolder:_serverUrl];
  428. // Actuate `Peek` feedback (weak boom)
  429. AudioServicesPlaySystemSound(1519);
  430. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  431. }
  432. - (void)setTitle
  433. {
  434. // Color text self.navigationItem.title
  435. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  436. if (_isSelectedMode) {
  437. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  438. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  439. self.navigationItem.titleView = nil;
  440. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  441. } else {
  442. // we are in home : LOGO BRAND
  443. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  444. self.navigationItem.title = nil;
  445. if ([app.reachability isReachable] == NO)
  446. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  447. else
  448. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  449. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  450. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  451. [singleTap setNumberOfTapsRequired:1];
  452. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  453. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  454. } else {
  455. self.navigationItem.title = _titleMain;
  456. }
  457. }
  458. }
  459. /*
  460. - (UIStatusBarStyle)preferredStatusBarStyle
  461. {
  462. UIBarStyle barStyle = self.navigationController.navigationBar.barStyle;
  463. if (barStyle == UIStatusBarStyleLightContent)
  464. return UIStatusBarStyleDefault;
  465. else
  466. return UIStatusBarStyleLightContent;
  467. }
  468. */
  469. - (void)setUINavigationBarDefault
  470. {
  471. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  472. UIBarButtonItem *buttonMore, *buttonNotification;
  473. // =
  474. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  475. buttonMore.enabled = true;
  476. // <
  477. self.navigationController.navigationBar.hidden = NO;
  478. // Notification
  479. if ([app.listOfNotifications count] > 0) {
  480. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  481. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  482. buttonNotification.enabled = true;
  483. }
  484. if (buttonNotification)
  485. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  486. else
  487. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  488. self.navigationItem.leftBarButtonItem = nil;
  489. }
  490. - (void)setUINavigationBarSelected
  491. {
  492. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  493. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  494. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  495. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  496. self.navigationItem.leftBarButtonItem = leftButton;
  497. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  498. }
  499. - (void)cancelSelect
  500. {
  501. [self tableViewSelect:NO];
  502. [app.reSelectMenu close];
  503. }
  504. - (void)closeAllMenu
  505. {
  506. // close Menu
  507. [app.reSelectMenu close];
  508. [app.reMainMenu close];
  509. // Close Menu Logo
  510. [CCMenuAccount dismissMenu];
  511. }
  512. #pragma --------------------------------------------------------------------------------------------
  513. #pragma mark ===== Document Picker =====
  514. #pragma --------------------------------------------------------------------------------------------
  515. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  516. {
  517. NSLog(@"Cancelled");
  518. }
  519. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  520. {
  521. NSLog(@"Cancelled");
  522. }
  523. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  524. {
  525. documentPicker.delegate = self;
  526. [self presentViewController:documentPicker animated:YES completion:nil];
  527. }
  528. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  529. {
  530. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  531. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  532. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  533. __block NSError *error;
  534. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  535. NSString *fileName = [url lastPathComponent];
  536. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  537. NSData *data = [NSData dataWithContentsOfURL:newURL];
  538. if (data && error == nil) {
  539. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  540. // Upload File
  541. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:serverUrl session:k_upload_session taskStatus: k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  542. } else {
  543. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  544. }
  545. } else {
  546. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  547. }
  548. }];
  549. }
  550. }
  551. - (void)openImportDocumentPicker
  552. {
  553. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  554. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  555. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  556. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  557. documentProviderMenu.delegate = self;
  558. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  559. }
  560. #pragma --------------------------------------------------------------------------------------------
  561. #pragma mark ===== Assets Picker =====
  562. #pragma --------------------------------------------------------------------------------------------
  563. -(void)dismissFormUploadAssets
  564. {
  565. [self reloadDatasource];
  566. }
  567. - (void)openAssetsPickerController
  568. {
  569. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  570. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  571. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  572. //UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil]; // DEPRECATED iOS9
  573. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[CTAssetsPickerController class]]];
  574. [app aspectNavigationControllerBar:navBar online:YES hidden:NO];
  575. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  576. dispatch_async(dispatch_get_main_queue(), ^{
  577. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  578. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  579. // init picker
  580. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  581. // set delegate
  582. picker.delegate = self;
  583. // to show selection order
  584. //picker.showsSelectionIndex = YES;
  585. // to present picker as a form sheet in iPad
  586. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  587. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  588. // present picker
  589. [self presentViewController:picker animated:YES completion:nil];
  590. });
  591. }];
  592. }
  593. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  594. {
  595. if (picker.selectedAssets.count > k_pickerControllerMax) {
  596. [app messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  597. return NO;
  598. }
  599. return YES;
  600. }
  601. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  602. {
  603. [picker dismissViewControllerAnimated:YES completion:^{
  604. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  605. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:assets cryptated:NO session:k_upload_session delegate:self];
  606. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  607. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  608. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  609. [self presentViewController:navigationController animated:YES completion:nil];
  610. }];
  611. }
  612. // New folder or new photo or video
  613. - (void)returnCreate:(NSInteger)type
  614. {
  615. switch (type) {
  616. case k_returnCreateFolderPlain: {
  617. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  618. NSString *message;
  619. UIAlertController *alertController;
  620. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  621. message = @"/";
  622. } else {
  623. message = [serverUrl lastPathComponent];
  624. }
  625. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  626. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  627. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  628. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  629. }];
  630. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  631. NSLog(@"Cancel action");
  632. }];
  633. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  634. UITextField *fileName = alertController.textFields.firstObject;
  635. [self createFolder:fileName.text serverUrl:serverUrl];
  636. }];
  637. okAction.enabled = NO;
  638. [alertController addAction:cancelAction];
  639. [alertController addAction:okAction];
  640. [self presentViewController:alertController animated:YES completion:nil];
  641. }
  642. break;
  643. case k_returnCreateFotoVideoPlain: {
  644. [self openAssetsPickerController];
  645. }
  646. break;
  647. case k_returnCreateFilePlain: {
  648. [self openImportDocumentPicker];
  649. }
  650. break;
  651. case k_returnCreateFotoVideoEncrypted: {
  652. [self openAssetsPickerController];
  653. }
  654. break;
  655. case k_returnCreateFileEncrypted: {
  656. [self openImportDocumentPicker];
  657. }
  658. break;
  659. case k_returnCreateFileText: {
  660. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  661. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  662. [self presentViewController:navigationController animated:YES completion:nil];
  663. }
  664. break;
  665. }
  666. }
  667. #pragma --------------------------------------------------------------------------------------------
  668. #pragma mark ===== Save selected File =====
  669. #pragma --------------------------------------------------------------------------------------------
  670. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  671. {
  672. if (error)
  673. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  674. else
  675. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  676. }
  677. - (void)saveSelectedFiles
  678. {
  679. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  680. return;
  681. NSLog(@"[LOG] Start download selected files ...");
  682. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  683. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  684. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  685. for (tableMetadata *metadata in metadatas) {
  686. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  687. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  688. if (serverUrl)
  689. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  690. }
  691. }
  692. [_hud hideHud];
  693. });
  694. [self tableViewSelect:NO];
  695. }
  696. #pragma --------------------------------------------------------------------------------------------
  697. #pragma mark === Delegate Login ===
  698. #pragma --------------------------------------------------------------------------------------------
  699. - (void)loginSuccess:(NSInteger)loginType
  700. {
  701. [self readFolder:_serverUrl];
  702. }
  703. - (void)loginDisappear
  704. {
  705. app.activeLogin = nil;
  706. }
  707. #pragma mark -
  708. #pragma --------------------------------------------------------------------------------------------
  709. #pragma mark ===== Peek & Pop =====
  710. #pragma --------------------------------------------------------------------------------------------
  711. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  712. {
  713. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  714. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  715. if (metadata.thumbnailExists) {
  716. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  717. if (cell) {
  718. previewingContext.sourceRect = cell.frame;
  719. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  720. vc.delegate = self;
  721. vc.metadata = metadata;
  722. return vc;
  723. }
  724. }
  725. return nil;
  726. }
  727. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  728. {
  729. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  730. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  731. }
  732. #pragma mark -
  733. #pragma --------------------------------------------------------------------------------------------
  734. #pragma mark ==== External Sites ====
  735. #pragma --------------------------------------------------------------------------------------------
  736. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  737. {
  738. [[NCManageDatabase sharedInstance] deleteExternalSites];
  739. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  740. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  741. }
  742. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  743. {
  744. NSString *error = [NSString stringWithFormat:@"Get external site failure error %lu, %@", (long)errorCode, message];
  745. NSLog(@"[LOG] %@", error);
  746. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get External Sites Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  747. }
  748. #pragma --------------------------------------------------------------------------------------------
  749. #pragma mark ==== Activity ====
  750. #pragma --------------------------------------------------------------------------------------------
  751. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  752. {
  753. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  754. // Reload Activity Data Source
  755. [app.activeActivity reloadDatasource];
  756. }
  757. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  758. {
  759. NSString *error = [NSString stringWithFormat:@"Get Activity Server failure error %lu, %@", (long)errorCode, message];
  760. NSLog(@"[LOG] %@", error);
  761. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Activity Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  762. }
  763. #pragma --------------------------------------------------------------------------------------------
  764. #pragma mark ==== Notification ====
  765. #pragma --------------------------------------------------------------------------------------------
  766. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  767. {
  768. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  769. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  770. // Order by date
  771. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  772. OCNotifications *notification1 = obj1, *notification2 = obj2;
  773. return [notification2.date compare: notification1.date];
  774. }];
  775. // verify if listOfNotifications is changed
  776. NSString *old = @"", *new = @"";
  777. for (OCNotifications *notification in listOfNotifications)
  778. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  779. for (OCNotifications *notification in appDelegate.listOfNotifications)
  780. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  781. if (![new isEqualToString:old]) {
  782. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  783. // reload Notification view
  784. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  785. }
  786. // Update NavigationBar
  787. if (!_isSelectedMode) {
  788. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  789. }
  790. });
  791. }
  792. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  793. {
  794. NSString *error = [NSString stringWithFormat:@"Get Notification Server failure error %lu, %@", (long)errorCode, message];
  795. NSLog(@"[LOG] %@", error);
  796. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Notification Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  797. // Update NavigationBar
  798. if (!_isSelectedMode)
  799. [self setUINavigationBarDefault];
  800. }
  801. - (void)viewNotification
  802. {
  803. if ([app.listOfNotifications count] > 0) {
  804. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  805. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  806. [self presentViewController:notificationVC animated:YES completion:nil];
  807. }
  808. }
  809. #pragma --------------------------------------------------------------------------------------------
  810. #pragma mark ==== User Profile ====
  811. #pragma --------------------------------------------------------------------------------------------
  812. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  813. {
  814. NSString *error = [NSString stringWithFormat:@"Get user profile failure error %lu, %@", (long)errorCode, message];
  815. NSLog(@"[LOG] %@", error);
  816. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get user profile Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  817. }
  818. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  819. {
  820. // Update User (+ userProfile.id)
  821. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  822. // Get Account Active
  823. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  824. // Setting App active account
  825. [app settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  826. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  827. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  828. //UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  829. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  830. if (avatar)
  831. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  832. else
  833. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  834. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  835. });
  836. }
  837. #pragma --------------------------------------------------------------------------------------------
  838. #pragma mark ==== Capabilities ====
  839. #pragma --------------------------------------------------------------------------------------------
  840. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  841. {
  842. // Unauthorized
  843. if (errorCode == kOCErrorServerUnauthorized)
  844. [app openLoginView:self loginType:loginModifyPasswordUser];
  845. NSString *error = [NSString stringWithFormat:@"Get Capabilities failure error %lu, %@", (long)errorCode, message];
  846. NSLog(@"[LOG] %@", error);
  847. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Capabilities of Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  848. // Change Theming color
  849. [app settingThemingColorBrand];
  850. }
  851. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  852. {
  853. // Update capabilities db
  854. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  855. // ------ THEMING -----------------------------------------------------------------------
  856. // Download Theming Background & Change Theming color
  857. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  858. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  859. //UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  860. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  861. if (themingBackground)
  862. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  863. else
  864. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  865. }
  866. dispatch_async(dispatch_get_main_queue(), ^{
  867. [app settingThemingColorBrand];
  868. });
  869. });
  870. // ------ SEARCH ------------------------------------------------------------------------
  871. // Search bar if change version
  872. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  873. [self cancelSearchBar];
  874. }
  875. // ------ GET SERVICE SERVER ------------------------------------------------------------
  876. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  877. // Read External Sites
  878. if (capabilities.isExternalSitesServerEnabled) {
  879. metadataNet.action = actionGetExternalSitesServer;
  880. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  881. }
  882. // Read Share
  883. if (capabilities.isFilesSharingAPIEnabled) {
  884. [app.sharesID removeAllObjects];
  885. metadataNet.action = actionReadShareServer;
  886. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  887. }
  888. // Read Notification
  889. metadataNet.action = actionGetNotificationServer;
  890. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  891. // Read User Profile
  892. metadataNet.action = actionGetUserProfile;
  893. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  894. // Read Activity
  895. metadataNet.action = actionGetActivityServer;
  896. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  897. }
  898. #pragma mark -
  899. #pragma --------------------------------------------------------------------------------------------
  900. #pragma mark ==== Request Server Information ====
  901. #pragma --------------------------------------------------------------------------------------------
  902. - (void)requestServerCapabilities
  903. {
  904. // test
  905. if (app.activeAccount.length == 0)
  906. return;
  907. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  908. metadataNet.action = actionGetCapabilities;
  909. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  910. }
  911. #pragma mark -
  912. #pragma --------------------------------------------------------------------------------------------
  913. #pragma mark ==== Middleware Ping ====
  914. #pragma --------------------------------------------------------------------------------------------
  915. - (void)middlewarePing
  916. {
  917. // test
  918. if (app.activeAccount.length == 0)
  919. return;
  920. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  921. metadataNet.action = actionMiddlewarePing;
  922. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  923. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  924. }
  925. #pragma mark -
  926. #pragma --------------------------------------------------------------------------------------------
  927. #pragma mark ==== Download Thumbnail Delegate ====
  928. #pragma --------------------------------------------------------------------------------------------
  929. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  930. {
  931. NSLog(@"[LOG] Download Thumbnail Failure error %lu, %@", (long)errorCode, message);
  932. }
  933. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  934. {
  935. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  936. if ([self indexPathIsValid:indexPath]) {
  937. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  938. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  939. }
  940. }
  941. #pragma --------------------------------------------------------------------------------------------
  942. #pragma mark ==== Download ====
  943. #pragma --------------------------------------------------------------------------------------------
  944. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  945. {
  946. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  947. // File do not exists on server, remove in local
  948. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  949. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  950. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  951. if (metadata.directory && serverUrl) {
  952. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  953. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  954. }
  955. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  956. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  957. }
  958. if ([selector isEqualToString:selectorLoadViewImage]) {
  959. dispatch_async(dispatch_get_main_queue(), ^{
  960. // Updating Detail
  961. if (app.activeDetail)
  962. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  963. // Updating Photos
  964. if (app.activePhotos)
  965. [app.activePhotos downloadFileFailure:errorCode];
  966. });
  967. } else {
  968. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  969. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  970. }
  971. [self reloadDatasource:serverUrl];
  972. }
  973. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  974. {
  975. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  976. if (metadata == nil)
  977. return;
  978. // Download
  979. if ([selector isEqualToString:selectorDownloadFile]) {
  980. [self reloadDatasource:serverUrl];
  981. }
  982. // Synchronized
  983. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  984. [self reloadDatasource:serverUrl];
  985. }
  986. // add Favorite
  987. if ([selector isEqualToString:selectorAddFavorite]) {
  988. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  989. }
  990. // open View File
  991. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  992. [self reloadDatasource:serverUrl];
  993. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  994. selector = selectorOpenIn;
  995. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  996. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  997. selector = selectorOpenIn;
  998. } else {
  999. _metadata = metadata;
  1000. if ([self shouldPerformSegue])
  1001. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1002. }
  1003. }
  1004. // Open with...
  1005. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1006. [self reloadDatasource:serverUrl];
  1007. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1008. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1009. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName]];
  1010. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1011. _docController.delegate = self;
  1012. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1013. }
  1014. // Save to Photo Album
  1015. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1016. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1017. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1018. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1019. if (image)
  1020. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1021. else
  1022. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1023. }
  1024. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1025. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1026. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName])) {
  1027. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1028. } else {
  1029. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1030. }
  1031. }
  1032. [self reloadDatasource:serverUrl];
  1033. }
  1034. // Copy File
  1035. if ([selector isEqualToString:selectorLoadCopy]) {
  1036. [self reloadDatasource:serverUrl];
  1037. [self copyFileToPasteboard:metadata];
  1038. }
  1039. //download file plist
  1040. if ([selector isEqualToString:selectorLoadPlist]) {
  1041. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1042. long countSelectorLoadPlist = 0;
  1043. for (NSOperation *operation in [app.netQueue operations]) {
  1044. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1045. countSelectorLoadPlist++;
  1046. }
  1047. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1048. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:directoryID] && directoryID) {
  1049. dispatch_async(dispatch_get_main_queue(), ^{
  1050. [self reloadDatasource:serverUrl];
  1051. });
  1052. }
  1053. });
  1054. }
  1055. //selectorLoadViewImage
  1056. if ([selector isEqualToString:selectorLoadViewImage]) {
  1057. // Detail
  1058. if (app.activeDetail)
  1059. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1060. // Photos
  1061. if (app.activePhotos)
  1062. [app.activePhotos downloadFileSuccess:metadata];
  1063. [self reloadDatasource:serverUrl];
  1064. }
  1065. // if exists postselector call self with selectorPost
  1066. if ([selectorPost length] > 0)
  1067. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1068. // Auto Download Upload
  1069. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1070. // ONLY BACKGROUND
  1071. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1072. } else {
  1073. // ONLY FOREFROUND
  1074. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1075. }
  1076. }
  1077. - (void)downloadSelectedFilesFolders
  1078. {
  1079. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1080. return;
  1081. NSLog(@"[LOG] Start download selected ...");
  1082. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1083. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1084. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1085. for (tableMetadata *metadata in selectedMetadatas) {
  1086. if (metadata.directory) {
  1087. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1088. if (serverUrl) {
  1089. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1090. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  1091. }
  1092. } else {
  1093. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  1094. }
  1095. }
  1096. [_hud hideHud];
  1097. });
  1098. [self tableViewSelect:NO];
  1099. }
  1100. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1101. {
  1102. }
  1103. #pragma --------------------------------------------------------------------------------------------
  1104. #pragma mark ===== Upload new Photos/Videos =====
  1105. #pragma --------------------------------------------------------------------------------------------
  1106. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1107. {
  1108. // Auto Download Upload
  1109. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1110. if ([[NCManageDatabase sharedInstance] getPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier] > k_priorityAutoUploadStop) {
  1111. // Change priority Auto Upload
  1112. if ([[NCManageDatabase sharedInstance] setPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier priority:k_priorityAutoUploadError]) {
  1113. // Activity
  1114. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1115. }
  1116. if (errorCode != kCFURLErrorCancelled)
  1117. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1118. } else {
  1119. // Delete record on Table Auto Upload
  1120. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:selector];
  1121. // Activity
  1122. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Too many error, file deleted" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1123. [app messageNotification:@"_upload_file_" description:@"Too many error, file deleted, see Activity for more info" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1124. }
  1125. } else {
  1126. // Read File test do not exists
  1127. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1128. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1129. // reUpload
  1130. if (metadata)
  1131. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1132. }
  1133. // Print error
  1134. else if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized) {
  1135. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1136. }
  1137. }
  1138. [self reloadDatasource:serverUrl];
  1139. }
  1140. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1141. {
  1142. // Auto Download Upload
  1143. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1144. // ONLY BACKGROUND
  1145. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1146. } else {
  1147. // ONLY FOREFROUND
  1148. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1149. }
  1150. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1151. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1152. [self readFolder:serverUrl];
  1153. } else {
  1154. [self reloadDatasource:serverUrl];
  1155. }
  1156. });
  1157. }
  1158. //
  1159. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1160. //
  1161. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1162. {
  1163. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1164. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1165. });
  1166. }
  1167. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1168. {
  1169. NSArray *assets = [arguments objectAtIndex:0];
  1170. NSString *serverUrl = [arguments objectAtIndex:1];
  1171. BOOL useSubFolder = [[arguments objectAtIndex:2] boolValue];
  1172. NSString *session = [arguments objectAtIndex:3];
  1173. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1174. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1175. if (!directoryID) return;
  1176. // if request create the folder for Photos & the subfolders
  1177. if ([autoUploadPath isEqualToString:serverUrl])
  1178. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1179. return;
  1180. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1181. for (PHAsset *asset in assets) {
  1182. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1183. NSDate *assetDate = asset.creationDate;
  1184. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1185. // Create serverUrl if use sub folder
  1186. if (useSubFolder) {
  1187. [formatter setDateFormat:@"yyyy"];
  1188. NSString *yearString = [formatter stringFromDate:assetDate];
  1189. [formatter setDateFormat:@"MM"];
  1190. NSString *monthString = [formatter stringFromDate:assetDate];
  1191. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1192. }
  1193. // Check if is in upload
  1194. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1195. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1196. if ([isRecordInSessions count] > 0) {
  1197. // next upload
  1198. continue;
  1199. } else {
  1200. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1201. metadataNet.action = actionReadFile;
  1202. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1203. metadataNet.fileName = fileName;
  1204. metadataNet.session = session;
  1205. metadataNet.selector = selectorReadFileUploadFile;
  1206. metadataNet.serverUrl = serverUrl;
  1207. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1208. }
  1209. }
  1210. }
  1211. #pragma --------------------------------------------------------------------------------------------
  1212. #pragma mark ==== Read File ====
  1213. #pragma --------------------------------------------------------------------------------------------
  1214. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1215. {
  1216. // Unauthorized
  1217. if (errorCode == kOCErrorServerUnauthorized)
  1218. [app openLoginView:self loginType:loginModifyPasswordUser];
  1219. // UploadFile
  1220. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1221. // File not exists
  1222. if (errorCode == 404) {
  1223. metadataNet.errorCode = 0;
  1224. metadataNet.selector = selectorUploadFile;
  1225. metadataNet.selectorPost = nil;
  1226. metadataNet.taskStatus = k_taskStatusResume;
  1227. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1228. } else {
  1229. // error ho many retry befor notification and go to on next asses
  1230. if (metadataNet.errorRetry < 3) {
  1231. // Retry read file
  1232. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1233. } else {
  1234. // STOP check file, view message error
  1235. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1236. }
  1237. }
  1238. }
  1239. }
  1240. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1241. {
  1242. // Read Folder
  1243. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1244. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1245. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1246. [self readFolder:metadataNet.serverUrl];
  1247. }
  1248. }
  1249. // UploadFile
  1250. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1251. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1252. metadataNet.selector = selectorUploadFile;
  1253. metadataNet.selectorPost = nil;
  1254. metadataNet.taskStatus = k_taskStatusResume;
  1255. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1256. }
  1257. }
  1258. - (void)readFileReloadFolder
  1259. {
  1260. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1261. return;
  1262. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1263. metadataNet.action = actionReadFile;
  1264. metadataNet.priority = NSOperationQueuePriorityHigh;
  1265. metadataNet.selector = selectorReadFileReloadFolder;
  1266. metadataNet.serverUrl = _serverUrl;
  1267. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1268. }
  1269. #pragma --------------------------------------------------------------------------------------------
  1270. #pragma mark ==== Read Folder ====
  1271. #pragma --------------------------------------------------------------------------------------------
  1272. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1273. {
  1274. // Unauthorized
  1275. if (errorCode == kOCErrorServerUnauthorized)
  1276. [app openLoginView:self loginType:loginModifyPasswordUser];
  1277. _loadingFolder = NO;
  1278. [self tableViewReloadData];
  1279. [_refreshControl endRefreshing];
  1280. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1281. // verify active user
  1282. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1283. if (message && [record.account isEqualToString:metadataNet.account])
  1284. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1285. [self reloadDatasource:metadataNet.serverUrl];
  1286. }
  1287. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1288. {
  1289. // verify active user
  1290. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1291. if (![record.account isEqualToString:metadataNet.account])
  1292. return;
  1293. // save father e update permission
  1294. if(!_isSearchMode && metadataFolder)
  1295. _fatherPermission = metadataFolder.permissions;
  1296. NSArray *recordsInSessions;
  1297. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1298. if (_isSearchMode) {
  1299. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1300. } else {
  1301. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1302. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1303. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1304. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1305. }
  1306. for (tableMetadata *metadata in metadatas) {
  1307. // verify if the record is in download/upload progress
  1308. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1309. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1310. // is in Download or Upload
  1311. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1312. continue;
  1313. }
  1314. }
  1315. // Insert in Array
  1316. [metadatasToInsertInDB addObject:metadata];
  1317. }
  1318. // insert in Database
  1319. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1320. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1321. // read plist
  1322. if (!_isSearchMode)
  1323. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1324. // File is changed ??
  1325. if (!_isSearchMode && metadatasToInsertInDB)
  1326. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1327. });
  1328. // Search Mode
  1329. if (_isSearchMode) {
  1330. // Fix managed -> Unmanaged _searchResultMetadatas
  1331. if (metadatasToInsertInDB)
  1332. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1333. [self reloadDatasource:metadataNet.serverUrl];
  1334. }
  1335. // this is the same directory
  1336. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1337. // reload
  1338. [self reloadDatasource:metadataNet.serverUrl];
  1339. // stoprefresh
  1340. [_refreshControl endRefreshing];
  1341. // Enable change user
  1342. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1343. _loadingFolder = NO;
  1344. [self tableViewReloadData];
  1345. }
  1346. }
  1347. - (void)readFolder:(NSString *)serverUrl
  1348. {
  1349. // init control
  1350. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1351. [_refreshControl endRefreshing];
  1352. return;
  1353. }
  1354. // Search Mode
  1355. if (_isSearchMode) {
  1356. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1357. _searchFileName = @""; // forced reload searchg
  1358. [self updateSearchResultsForSearchController:self.searchController];
  1359. return;
  1360. }
  1361. _loadingFolder = YES;
  1362. [self tableViewReloadData];
  1363. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1364. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1365. metadataNet.action = actionReadFolder;
  1366. metadataNet.date = [NSDate date];
  1367. metadataNet.depth = @"1";
  1368. metadataNet.directoryID = directory.directoryID;
  1369. metadataNet.priority = NSOperationQueuePriorityHigh;
  1370. metadataNet.selector = selectorReadFolder;
  1371. metadataNet.serverUrl = serverUrl;
  1372. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1373. }
  1374. #pragma mark -
  1375. #pragma --------------------------------------------------------------------------------------------
  1376. #pragma mark ===== Search =====
  1377. #pragma --------------------------------------------------------------------------------------------
  1378. -(void)searchStartTimer
  1379. {
  1380. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1381. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1382. _noFilesSearchTitle = @"";
  1383. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1384. [self.tableView reloadEmptyDataSet];
  1385. }
  1386. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1387. {
  1388. //[self setNeedsStatusBarAppearanceUpdate];
  1389. _isSearchMode = YES;
  1390. [self deleteRefreshControl];
  1391. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1392. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1393. _searchFileName = fileName;
  1394. // First : filter
  1395. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1396. if (!directoryID) return;
  1397. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileName CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1398. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1399. [_searchResultMetadatas removeAllObjects];
  1400. for (tableMetadata *record in records)
  1401. [_searchResultMetadatas addObject:record];
  1402. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1403. metadataNet.account = app.activeAccount;
  1404. metadataNet.directoryID = directoryID;
  1405. metadataNet.selector = selectorSearch;
  1406. metadataNet.serverUrl = _serverUrl;
  1407. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1408. // Version >= 12
  1409. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1410. [_timerWaitInput invalidate];
  1411. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1412. }
  1413. }
  1414. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1415. [self reloadDatasource];
  1416. }
  1417. }
  1418. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1419. {
  1420. [self cancelSearchBar];
  1421. [self readFolder:_serverUrl];
  1422. }
  1423. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1424. {
  1425. // Unauthorized
  1426. if (errorCode == kOCErrorServerUnauthorized)
  1427. [app openLoginView:self loginType:loginModifyPasswordUser];
  1428. if (message && errorCode != kOCErrorServerUnauthorized)
  1429. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1430. _searchFileName = @"";
  1431. }
  1432. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1433. {
  1434. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1435. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1436. }
  1437. - (void)cancelSearchBar
  1438. {
  1439. if (self.searchController.active) {
  1440. [self.searchController setActive:NO];
  1441. [self createRefreshControl];
  1442. _isSearchMode = NO;
  1443. _searchFileName = @"";
  1444. _dateReadDataSource = nil;
  1445. _searchResultMetadatas = [NSMutableArray new];
  1446. [self reloadDatasource];
  1447. }
  1448. //[self setNeedsStatusBarAppearanceUpdate];
  1449. }
  1450. #pragma mark -
  1451. #pragma --------------------------------------------------------------------------------------------
  1452. #pragma mark ===== Delete File or Folder =====
  1453. #pragma --------------------------------------------------------------------------------------------
  1454. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1455. {
  1456. // Unauthorized
  1457. if (errorCode == kOCErrorServerUnauthorized)
  1458. [app openLoginView:self loginType:loginModifyPasswordUser];
  1459. NSLog(@"[LOG] Delete File failure error %lu, %@", (long)errorCode, message);
  1460. [self deleteFileOrFolderSuccess:metadataNet];
  1461. }
  1462. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1463. {
  1464. [_queueSelector removeObject:metadataNet.selector];
  1465. if ([_queueSelector count] == 0) {
  1466. [_hud hideHud];
  1467. // next
  1468. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1469. if ([_selectedFileIDsMetadatas count] > 0) {
  1470. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1471. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1472. } else {
  1473. // End Select Table View
  1474. [self tableViewSelect:NO];
  1475. // Reload
  1476. if (_isSearchMode)
  1477. [self readFolder:metadataNet.serverUrl];
  1478. else
  1479. [self reloadDatasource:metadataNet.serverUrl];
  1480. }
  1481. }
  1482. }
  1483. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1484. {
  1485. [_queueSelector addObject:selectorDelete];
  1486. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1487. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1488. }
  1489. - (void)deleteFile
  1490. {
  1491. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1492. return;
  1493. [_queueSelector removeAllObjects];
  1494. if ([_selectedFileIDsMetadatas count] > 0) {
  1495. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1496. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1497. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1498. } else {
  1499. _numSelectedFileIDsMetadatas = 1;
  1500. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1501. }
  1502. }
  1503. #pragma --------------------------------------------------------------------------------------------
  1504. #pragma mark ===== Rename / Move =====
  1505. #pragma --------------------------------------------------------------------------------------------
  1506. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1507. {
  1508. [self readFolder:metadataNet.serverUrl];
  1509. }
  1510. - (void)renameFile:(NSArray *)arguments
  1511. {
  1512. tableMetadata* metadata = [arguments objectAtIndex:0];
  1513. NSString *fileName = [arguments objectAtIndex:1];
  1514. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1515. }
  1516. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1517. {
  1518. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1519. [_hud hideHud];
  1520. if (message && errorCode != kOCErrorServerUnauthorized)
  1521. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1522. // End Select Table View
  1523. [self tableViewSelect:NO];
  1524. // reload Datasource
  1525. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1526. [self readFolder:metadataNet.serverUrl];
  1527. else
  1528. [self reloadDatasource];
  1529. }
  1530. }
  1531. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1532. {
  1533. [_queueSelector removeObject:metadataNet.selector];
  1534. if ([_queueSelector count] == 0) {
  1535. [_hud hideHud];
  1536. NSString *fileName = metadataNet.fileName;
  1537. NSString *directoryID = metadataNet.directoryID;
  1538. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1539. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1540. if (!serverUrlTo) return;
  1541. // FILE -> Metadata
  1542. if (metadataNet.directory == NO)
  1543. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1544. // DIRECTORY -> Directory - CCMetadata
  1545. if (metadataNet.directory == YES) {
  1546. // delete all dir / subdir
  1547. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1548. // move metadata
  1549. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1550. // Add new directory
  1551. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1552. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1553. }
  1554. // next
  1555. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1556. if ([_selectedFileIDsMetadatas count] > 0) {
  1557. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1558. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1559. } else {
  1560. // End Select Table View
  1561. [self tableViewSelect:NO];
  1562. // reload Datasource
  1563. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1564. [self readFolder:metadataNet.serverUrl];
  1565. else
  1566. [self reloadDatasource];
  1567. }
  1568. }
  1569. }
  1570. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1571. {
  1572. tableMetadata *metadata = [arguments objectAtIndex:0];
  1573. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1574. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1575. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1576. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1577. if (!serverUrl) return;
  1578. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1579. if (!directoryIDTo) return;
  1580. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withUserID:app.activeUserID withPassword:app.activePassword withUrl:app.activeUrl];
  1581. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1582. if(!error) {
  1583. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1584. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1585. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1586. }];
  1587. [alert addAction:ok];
  1588. [self presentViewController:alert animated:YES completion:nil];
  1589. });
  1590. // End Select Table View
  1591. [self tableViewSelect:NO];
  1592. // reload Datasource
  1593. [self readFileReloadFolder];
  1594. return;
  1595. }
  1596. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1597. metadataNet.action = actionMoveFileOrFolder;
  1598. metadataNet.directory = metadata.directory;
  1599. metadataNet.fileID = metadata.fileID;
  1600. metadataNet.directoryID = metadata.directoryID;
  1601. metadataNet.directoryIDTo = directoryIDTo;
  1602. metadataNet.fileName = metadata.fileName;
  1603. metadataNet.fileNameTo = metadata.fileName;
  1604. metadataNet.etag = metadata.etag;
  1605. metadataNet.selector = selectorMove;
  1606. metadataNet.serverUrl = serverUrl;
  1607. metadataNet.serverUrlTo = serverUrlTo;
  1608. [_queueSelector addObject:metadataNet.selector];
  1609. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1610. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1611. }
  1612. // DELEGATE : Move
  1613. - (void)dismissMove
  1614. {
  1615. [self reloadDatasource];
  1616. }
  1617. // DELEGATE : Move
  1618. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1619. {
  1620. [_queueSelector removeAllObjects];
  1621. if ([_selectedFileIDsMetadatas count] > 0) {
  1622. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1623. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1624. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1625. } else {
  1626. _numSelectedFileIDsMetadatas = 1;
  1627. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1628. }
  1629. }
  1630. - (void)moveOpenWindow:(NSArray *)indexPaths
  1631. {
  1632. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1633. return;
  1634. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1635. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1636. viewController.delegate = self;
  1637. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1638. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1639. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1640. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1641. viewController.networkingOperationQueue = app.netQueue;
  1642. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1643. [self presentViewController:navigationController animated:YES completion:nil];
  1644. }
  1645. #pragma --------------------------------------------------------------------------------------------
  1646. #pragma mark ===== Create folder =====
  1647. #pragma --------------------------------------------------------------------------------------------
  1648. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1649. {
  1650. // Unauthorized
  1651. if (errorCode == kOCErrorServerUnauthorized)
  1652. [app openLoginView:self loginType:loginModifyPasswordUser];
  1653. if (message && errorCode != kOCErrorServerUnauthorized)
  1654. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1655. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1656. [self reloadDatasource];
  1657. // We are in directory fail ?
  1658. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1659. if (vc)
  1660. [vc.navigationController popViewControllerAnimated:YES];
  1661. }
  1662. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1663. {
  1664. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1665. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1666. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1667. if (metadata) {
  1668. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1669. metadata.fileID = metadataNet.fileID;
  1670. metadata.date = metadataNet.date;
  1671. metadata.permissions = @"RDNVCK";
  1672. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1673. [self reloadDatasource];
  1674. } else {
  1675. [self readFileReloadFolder];
  1676. }
  1677. }
  1678. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1679. {
  1680. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1681. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1682. if (![fileNameFolder length]) return;
  1683. //if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1684. //else metadataNet.serverUrl = _serverUrl;
  1685. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1686. if (!directoryID) return;
  1687. metadataNet.action = actionCreateFolder;
  1688. metadataNet.directoryID = directoryID;
  1689. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1690. metadataNet.fileName = fileNameFolder;
  1691. metadataNet.selector = selectorCreateFolder;
  1692. metadataNet.serverUrl = serverUrl;
  1693. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1694. // Create Directory on metadata
  1695. tableMetadata *metadata = [CCUtility createMetadataWithAccount:app.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1696. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1697. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1698. [self reloadDatasource];
  1699. }
  1700. #pragma --------------------------------------------------------------------------------------------
  1701. #pragma mark ===== Encrypted / Decrypted Folder =====
  1702. #pragma --------------------------------------------------------------------------------------------
  1703. - (void)encyptedDecryptedFolder
  1704. {
  1705. }
  1706. #pragma --------------------------------------------------------------------------------------------
  1707. #pragma mark ===== Encrypted/Decrypted File =====
  1708. #pragma --------------------------------------------------------------------------------------------
  1709. - (void)encryptedSelectedFiles
  1710. {
  1711. }
  1712. - (void)decryptedSelectedFiles
  1713. {
  1714. }
  1715. - (void)cmdEncryptedDecryptedFile
  1716. {
  1717. }
  1718. - (void)encryptedFile:(tableMetadata *)metadata
  1719. {
  1720. }
  1721. - (void)decryptedFile:(tableMetadata *)metadata
  1722. {
  1723. }
  1724. #pragma --------------------------------------------------------------------------------------------
  1725. #pragma mark ===== Progress & Task Button =====
  1726. #pragma --------------------------------------------------------------------------------------------
  1727. - (void)triggerProgressTask:(NSNotification *)notification
  1728. {
  1729. NSDictionary *dict = notification.userInfo;
  1730. NSString *fileID = [dict valueForKey:@"fileID"];
  1731. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1732. float progress = [[dict valueForKey:@"progress"] floatValue];
  1733. // CCProgress
  1734. if (progress == 0)
  1735. [self.navigationController cancelCCProgress];
  1736. else
  1737. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1738. // Check
  1739. if (!fileID || [fileID isEqualToString: @""])
  1740. return;
  1741. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1742. if (![serverUrl isEqualToString:_serverUrl])
  1743. return;
  1744. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1745. if ([self indexPathIsValid:indexPath]) {
  1746. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1747. cell.progressView.progressTintColor = [UIColor blackColor];
  1748. cell.progressView.hidden = NO;
  1749. [cell.progressView setProgress:progress];
  1750. }
  1751. }
  1752. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1753. {
  1754. UITouch * touch = [[event allTouches] anyObject];
  1755. CGPoint location = [touch locationInView:self.tableView];
  1756. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1757. if ([self indexPathIsValid:indexPath]) {
  1758. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1759. if (metadata)
  1760. [self reloadTaskButton:metadata];
  1761. }
  1762. }
  1763. - (void)reloadTaskButton:(tableMetadata *)metadata
  1764. {
  1765. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1766. __block NSURLSessionTask *findTask;
  1767. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1768. NSString *fileID = metadata.fileID;
  1769. // DOWNLOAD
  1770. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1771. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1772. for (NSURLSessionUploadTask *task in downloadTasks)
  1773. if (task.taskIdentifier == sessionTaskIdentifier) {
  1774. findTask = task;
  1775. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1776. [task cancel];
  1777. }
  1778. if (!findTask) {
  1779. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1780. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1781. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1782. }
  1783. }];
  1784. }
  1785. // UPLOAD
  1786. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1787. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1788. for (NSURLSessionUploadTask *task in uploadTasks)
  1789. if (task.taskIdentifier == sessionTaskIdentifier) {
  1790. findTask = task;
  1791. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1792. [task cancel];
  1793. }
  1794. if (!findTask) {
  1795. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1796. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1797. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1798. }
  1799. }];
  1800. }
  1801. }
  1802. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1803. {
  1804. UITouch * touch = [[event allTouches] anyObject];
  1805. CGPoint location = [touch locationInView:self.tableView];
  1806. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1807. if ([self indexPathIsValid:indexPath]) {
  1808. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1809. if (metadata)
  1810. [self cancelTaskButton:metadata reloadTable:YES];
  1811. }
  1812. }
  1813. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1814. {
  1815. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1816. __block NSURLSessionTask *findTask;
  1817. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1818. NSString *fileID = metadata.fileID;
  1819. // DOWNLOAD
  1820. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1821. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1822. for (NSURLSessionTask *task in downloadTasks)
  1823. if (task.taskIdentifier == sessionTaskIdentifier) {
  1824. findTask = task;
  1825. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1826. [task cancel];
  1827. }
  1828. if (!findTask) {
  1829. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1830. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1831. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1832. }
  1833. }];
  1834. }
  1835. // UPLOAD
  1836. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1837. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1838. for (NSURLSessionUploadTask *task in uploadTasks)
  1839. if (task.taskIdentifier == sessionTaskIdentifier) {
  1840. findTask = task;
  1841. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1842. [task cancel];
  1843. }
  1844. if (!findTask) {
  1845. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1846. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1847. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1848. }
  1849. }];
  1850. }
  1851. }
  1852. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1853. {
  1854. UITouch * touch = [[event allTouches] anyObject];
  1855. CGPoint location = [touch locationInView:self.tableView];
  1856. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1857. if ([self indexPathIsValid:indexPath]) {
  1858. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1859. if (metadata)
  1860. [self stopTaskButton:metadata];
  1861. }
  1862. }
  1863. - (void)stopTaskButton:(tableMetadata *)metadata
  1864. {
  1865. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1866. __block NSURLSessionTask *findTask;
  1867. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1868. NSString *fileID = metadata.fileID;
  1869. // UPLOAD
  1870. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1871. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1872. for (NSURLSessionUploadTask *task in uploadTasks)
  1873. if (task.taskIdentifier == sessionTaskIdentifier) {
  1874. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1875. findTask = task;
  1876. [task cancel];
  1877. }
  1878. if (!findTask) {
  1879. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1880. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1881. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1882. }
  1883. }];
  1884. }
  1885. }
  1886. #pragma --------------------------------------------------------------------------------------------
  1887. #pragma mark ===== Shared =====
  1888. #pragma --------------------------------------------------------------------------------------------
  1889. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1890. {
  1891. [_hud hideHud];
  1892. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1893. // change account ?
  1894. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1895. if([record.account isEqualToString:metadataNet.account] == NO)
  1896. return;
  1897. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1898. if (result) {
  1899. appDelegate.sharesLink = result[0];
  1900. appDelegate.sharesUserAndGroup = result[1];
  1901. }
  1902. // Notify Shares View
  1903. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1904. if (openWindow) {
  1905. if (_shareOC) {
  1906. [_shareOC reloadData];
  1907. } else {
  1908. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1909. // Apriamo la view
  1910. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1911. _shareOC.delegate = self;
  1912. _shareOC.metadata = metadata;
  1913. _shareOC.serverUrl = metadataNet.serverUrl;
  1914. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  1915. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  1916. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1917. [self presentViewController:_shareOC animated:YES completion:nil];
  1918. }
  1919. }
  1920. [self tableViewReloadData];
  1921. }
  1922. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1923. {
  1924. [_hud hideHud];
  1925. // Unauthorized
  1926. if (errorCode == kOCErrorServerUnauthorized)
  1927. [app openLoginView:self loginType:loginModifyPasswordUser];
  1928. if (errorCode != kOCErrorServerUnauthorized)
  1929. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1930. if (_shareOC)
  1931. [_shareOC reloadData];
  1932. [self tableViewReloadData];
  1933. }
  1934. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1935. {
  1936. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1937. metadataNet.action = actionShare;
  1938. metadataNet.fileID = metadata.fileID;
  1939. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  1940. metadataNet.password = password;
  1941. metadataNet.selector = selectorShare;
  1942. metadataNet.serverUrl = serverUrl;
  1943. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1944. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1945. }
  1946. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1947. {
  1948. [_hud hideHud];
  1949. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1950. // rimuoviamo la condivisione da db
  1951. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1952. if (result) {
  1953. appDelegate.sharesLink = result[0];
  1954. appDelegate.sharesUserAndGroup = result[1];
  1955. }
  1956. if (_shareOC)
  1957. [_shareOC reloadData];
  1958. [self tableViewReloadData];
  1959. }
  1960. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1961. {
  1962. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1963. metadataNet.action = actionUnShare;
  1964. metadataNet.fileID = metadata.fileID;
  1965. metadataNet.fileName = metadata.fileName;
  1966. metadataNet.selector = selectorUnshare;
  1967. metadataNet.serverUrl = serverUrl;
  1968. metadataNet.share = share;
  1969. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1970. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1971. }
  1972. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1973. {
  1974. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1975. metadataNet.action = actionUpdateShare;
  1976. metadataNet.fileID = metadata.fileID;
  1977. metadataNet.expirationTime = expirationTime;
  1978. metadataNet.password = password;
  1979. metadataNet.selector = selectorUpdateShare;
  1980. metadataNet.serverUrl = serverUrl;
  1981. metadataNet.share = share;
  1982. metadataNet.sharePermission = permission;
  1983. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1984. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1985. }
  1986. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1987. {
  1988. [_hud hideHud];
  1989. if (_shareOC)
  1990. [_shareOC reloadUserAndGroup:items];
  1991. }
  1992. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1993. {
  1994. [_hud hideHud];
  1995. // Unauthorized
  1996. if (errorCode == kOCErrorServerUnauthorized)
  1997. [app openLoginView:self loginType:loginModifyPasswordUser];
  1998. if (errorCode != kOCErrorServerUnauthorized)
  1999. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2000. }
  2001. - (void)getUserAndGroup:(NSString *)find
  2002. {
  2003. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2004. metadataNet.action = actionGetUserAndGroup;
  2005. metadataNet.options = find;
  2006. metadataNet.selector = selectorGetUserAndGroup;
  2007. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2008. [_hud visibleIndeterminateHud];
  2009. }
  2010. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2011. {
  2012. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2013. metadataNet.action = actionShareWith;
  2014. metadataNet.fileID = metadata.fileID;
  2015. metadataNet.directoryID = directoryID;
  2016. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2017. metadataNet.serverUrl = serverUrl;
  2018. metadataNet.selector = selectorShare;
  2019. metadataNet.share = user;
  2020. metadataNet.shareeType = shareeType;
  2021. metadataNet.sharePermission = permission;
  2022. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2023. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2024. }
  2025. - (void)openWindowShare:(tableMetadata *)metadata
  2026. {
  2027. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2028. if (!serverUrl) return;
  2029. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2030. metadataNet.action = actionReadShareServer;
  2031. metadataNet.fileID = metadata.fileID;
  2032. metadataNet.fileName = metadata.fileName;
  2033. metadataNet.selector = selectorOpenWindowShare;
  2034. metadataNet.serverUrl = serverUrl;
  2035. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2036. [_hud visibleIndeterminateHud];
  2037. }
  2038. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2039. {
  2040. CGPoint location = [tapGesture locationInView:self.tableView];
  2041. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2042. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2043. if (metadata)
  2044. [self openWindowShare:metadata];
  2045. }
  2046. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2047. {
  2048. CGPoint location = [tapGesture locationInView:self.tableView];
  2049. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2050. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2051. if (metadata) {
  2052. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2053. vc.metadata = metadata;
  2054. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2055. [self presentViewController:vc animated:YES completion:nil];
  2056. }
  2057. }
  2058. #pragma --------------------------------------------------------------------------------------------
  2059. #pragma mark ===== Favorite =====
  2060. #pragma --------------------------------------------------------------------------------------------
  2061. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2062. {
  2063. _dateReadDataSource = nil;
  2064. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2065. if (_isSearchMode)
  2066. [self readFolder:metadataNet.serverUrl];
  2067. else
  2068. [self reloadDatasource:metadataNet.serverUrl];
  2069. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2070. if (metadata.directory && metadata.favorite) {
  2071. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2072. [app.activeFavorites addFavoriteFolder:dir];
  2073. }
  2074. }
  2075. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2076. {
  2077. // Unauthorized
  2078. if (errorCode == kOCErrorServerUnauthorized)
  2079. [app openLoginView:self loginType:loginModifyPasswordUser];
  2080. NSLog(@"[LOG] Setting Favorite failure error %lu, %@", (long)errorCode, message);
  2081. }
  2082. - (void)addFavorite:(tableMetadata *)metadata
  2083. {
  2084. if (metadata.directory) {
  2085. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2086. } else {
  2087. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2088. if (serverUrl)
  2089. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2090. }
  2091. }
  2092. - (void)removeFavorite:(tableMetadata *)metadata
  2093. {
  2094. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2095. }
  2096. #pragma --------------------------------------------------------------------------------------------
  2097. #pragma mark ===== Open in... =====
  2098. #pragma --------------------------------------------------------------------------------------------
  2099. - (void)openIn:(tableMetadata *)metadata
  2100. {
  2101. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2102. if (!serverUrl) return;
  2103. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2104. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2105. if ([self indexPathIsValid:indexPath])
  2106. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2107. }
  2108. #pragma --------------------------------------------------------------------------------------------
  2109. #pragma mark ===== Remove Local File =====
  2110. #pragma --------------------------------------------------------------------------------------------
  2111. - (void)removeLocalFile:(tableMetadata *)metadata
  2112. {
  2113. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2114. if (!serverUrl) return;
  2115. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2116. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2117. [self reloadDatasource:serverUrl];
  2118. }
  2119. #pragma --------------------------------------------------------------------------------------------
  2120. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2121. #pragma --------------------------------------------------------------------------------------------
  2122. - (void)orderTable:(NSString *)order
  2123. {
  2124. [CCUtility setOrderSettings:order];
  2125. // Clear data-read of DataSource
  2126. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2127. }
  2128. - (void)ascendingTable:(BOOL)ascending
  2129. {
  2130. [CCUtility setAscendingSettings:ascending];
  2131. // Clear data-read of DataSource
  2132. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2133. }
  2134. - (void)directoryOnTop:(BOOL)directoryOnTop
  2135. {
  2136. [CCUtility setDirectoryOnTop:directoryOnTop];
  2137. // Clear data-read of DataSource
  2138. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2139. }
  2140. - (void)tableGroupBy:(NSString *)groupBy
  2141. {
  2142. [CCUtility setGroupBySettings:groupBy];
  2143. // Clear data-read of DataSource
  2144. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2145. }
  2146. #pragma --------------------------------------------------------------------------------------------
  2147. #pragma mark ==== Menu LOGO ====
  2148. #pragma --------------------------------------------------------------------------------------------
  2149. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2150. {
  2151. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2152. return;
  2153. // Brand
  2154. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2155. return;
  2156. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", app.activeAccount] sorted:nil ascending:NO] count];
  2157. NSUInteger numInQueue = [app.netQueue operationCount];
  2158. if (numInSession+numInQueue > 0) {
  2159. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2160. return;
  2161. }
  2162. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2163. NSMutableArray *menuArray = [NSMutableArray new];
  2164. for (NSString *account in listAccount) {
  2165. if ([account isEqualToString:app.activeAccount]) continue;
  2166. CCMenuItem *item = [[CCMenuItem alloc] init];
  2167. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2168. item.argument = account;
  2169. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2170. item.target = self;
  2171. item.action = @selector(changeDefaultAccount:);
  2172. [menuArray addObject:item];
  2173. }
  2174. if ([menuArray count] == 0)
  2175. return;
  2176. OptionalConfiguration options;
  2177. Color textColor, backgroundColor;
  2178. textColor.R = 0;
  2179. textColor.G = 0;
  2180. textColor.B = 0;
  2181. backgroundColor.R = 1;
  2182. backgroundColor.G = 1;
  2183. backgroundColor.B = 1;
  2184. options.arrowSize = 9;
  2185. options.marginXSpacing = 7;
  2186. options.marginYSpacing = 10;
  2187. options.intervalSpacing = 20;
  2188. options.menuCornerRadius = 6.5;
  2189. options.maskToBackground = NO;
  2190. options.shadowOfMenu = YES;
  2191. options.hasSeperatorLine = YES;
  2192. options.seperatorLineHasInsets = YES;
  2193. options.textColor = textColor;
  2194. options.menuBackgroundColor = backgroundColor;
  2195. CGRect rect = self.view.frame;
  2196. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2197. CGFloat safeAreaTop = 0;
  2198. CGFloat offsetY = 35;
  2199. if (@available(iOS 11, *)) {
  2200. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2201. }
  2202. rect.origin.y = locationY + safeAreaTop + offsetY;
  2203. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2204. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2205. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2206. }
  2207. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2208. {
  2209. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2210. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2211. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2212. if (tableAccount)
  2213. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2214. // go to home sweet home
  2215. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2216. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2217. });
  2218. }
  2219. #pragma --------------------------------------------------------------------------------------------
  2220. #pragma mark ==== ReMenu ====
  2221. #pragma --------------------------------------------------------------------------------------------
  2222. - (void)createReMenuBackgroundView:(REMenu *)menu
  2223. {
  2224. UILayoutGuide *layoutGuide;
  2225. if (@available(iOS 11, *)) {
  2226. layoutGuide = [UIApplication sharedApplication].delegate.window.safeAreaLayoutGuide;
  2227. }
  2228. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2229. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2230. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, rootController.view.frame.size.width, rootController.view.frame.size.height);
  2231. [UIView animateWithDuration:0.2 animations:^{
  2232. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height + 40;
  2233. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, self.view.frame.size.width, - y);
  2234. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2235. }];
  2236. }
  2237. - (void)createReMainMenu
  2238. {
  2239. NSString *ordinamento;
  2240. NSString *groupBy = _directoryGroupBy;
  2241. __block NSString *nuovoOrdinamento;
  2242. NSString *titoloNuovo, *titoloAttuale;
  2243. BOOL ascendente;
  2244. __block BOOL nuovoAscendente;
  2245. UIImage *image;
  2246. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2247. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2248. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2249. [self tableViewSelect:YES];
  2250. }
  2251. }];
  2252. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2253. ordinamento = _directoryOrder;
  2254. if ([ordinamento isEqualToString:@"fileName"]) {
  2255. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2256. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2257. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2258. nuovoOrdinamento = @"date";
  2259. }
  2260. if ([ordinamento isEqualToString:@"date"]) {
  2261. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2262. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2263. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2264. nuovoOrdinamento = @"fileName";
  2265. }
  2266. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2267. [self orderTable:nuovoOrdinamento];
  2268. }];
  2269. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2270. ascendente = [CCUtility getAscendingSettings];
  2271. if (ascendente) {
  2272. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2273. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2274. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2275. nuovoAscendente = false;
  2276. }
  2277. if (!ascendente) {
  2278. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2279. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2280. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2281. nuovoAscendente = true;
  2282. }
  2283. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2284. [self ascendingTable:nuovoAscendente];
  2285. }];
  2286. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2287. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2288. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2289. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2290. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2291. else [self tableGroupBy:@"alphabetic"];
  2292. }];
  2293. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2294. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2295. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2296. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2297. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2298. else [self tableGroupBy:@"typefile"];
  2299. }];
  2300. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2301. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2302. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2303. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2304. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2305. else [self tableGroupBy:@"date"];
  2306. }];
  2307. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2308. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2309. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2310. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2311. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2312. else [self directoryOnTop:YES];
  2313. }];
  2314. // REMENU --------------------------------------------------------------------------------------------------------------
  2315. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2316. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2317. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2318. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2319. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2320. app.reMainMenu.separatorHeight = 0.5;
  2321. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2322. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2323. app.reMainMenu.textColor = [UIColor blackColor];
  2324. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2325. app.reMainMenu.textShadowColor = nil;
  2326. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2327. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2328. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2329. app.reMainMenu.highlightedSeparatorColor = nil;
  2330. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2331. app.reMainMenu.highlightedTextShadowColor = nil;
  2332. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2333. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2334. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2335. app.reMainMenu.subtitleTextShadowColor = nil;
  2336. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2337. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2338. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2339. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2340. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2341. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2342. app.reMainMenu.borderWidth = 0.3;
  2343. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2344. app.reMainMenu.animationDuration = 0.2;
  2345. app.reMainMenu.closeAnimationDuration = 0.2;
  2346. app.reMainMenu.bounce = NO;
  2347. [app.reMainMenu setClosePreparationBlock:^{
  2348. // Backgroun reMenu (Gesture)
  2349. [_reMenuBackgroundView removeFromSuperview];
  2350. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2351. }];
  2352. }
  2353. - (void)toggleReMainMenu
  2354. {
  2355. if (app.reMainMenu.isOpen) {
  2356. [app.reMainMenu close];
  2357. } else {
  2358. [self createReMainMenu];
  2359. [app.reMainMenu showFromNavigationController:self.navigationController];
  2360. // Backgroun reMenu & (Gesture)
  2361. if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
  2362. [self createReMenuBackgroundView:app.reMainMenu];
  2363. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2364. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2365. }
  2366. }
  2367. - (void)createReSelectMenu
  2368. {
  2369. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2370. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2371. [self deleteFile];
  2372. }];
  2373. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2374. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2375. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2376. }];
  2377. /*
  2378. if (app.isCryptoCloudMode) {
  2379. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2380. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2381. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2382. }];
  2383. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2384. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2385. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2386. }];
  2387. }
  2388. */
  2389. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2390. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2391. [self downloadSelectedFilesFolders];
  2392. }];
  2393. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2394. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2395. [self saveSelectedFiles];
  2396. }];
  2397. // REMENU --------------------------------------------------------------------------------------------------------------
  2398. /*
  2399. if (app.isCryptoCloudMode) {
  2400. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2401. } else {
  2402. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2403. }
  2404. */
  2405. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2406. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2407. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2408. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2409. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2410. app.reSelectMenu.separatorHeight = 0.5;
  2411. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2412. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2413. app.reSelectMenu.textColor = [UIColor blackColor];
  2414. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2415. app.reSelectMenu.textShadowColor = nil;
  2416. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2417. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2418. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2419. app.reSelectMenu.highlightedSeparatorColor = nil;
  2420. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2421. app.reSelectMenu.highlightedTextShadowColor = nil;
  2422. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2423. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2424. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2425. app.reSelectMenu.subtitleTextShadowColor = nil;
  2426. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2427. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2428. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2429. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2430. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2431. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2432. app.reSelectMenu.borderWidth = 0.3;
  2433. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2434. app.reSelectMenu.closeAnimationDuration = 0.2;
  2435. app.reSelectMenu.animationDuration = 0.2;
  2436. app.reSelectMenu.bounce = NO;
  2437. [app.reSelectMenu setClosePreparationBlock:^{
  2438. // Backgroun reMenu (Gesture)
  2439. [_reMenuBackgroundView removeFromSuperview];
  2440. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2441. }];
  2442. }
  2443. - (void)toggleReSelectMenu
  2444. {
  2445. if (app.reSelectMenu.isOpen) {
  2446. [app.reSelectMenu close];
  2447. } else {
  2448. [self createReSelectMenu];
  2449. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2450. // Backgroun reMenu & (Gesture)
  2451. if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
  2452. [self createReMenuBackgroundView:app.reSelectMenu];
  2453. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2454. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2455. }
  2456. }
  2457. #pragma --------------------------------------------------------------------------------------------
  2458. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2459. #pragma --------------------------------------------------------------------------------------------
  2460. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2461. {
  2462. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2463. UITableView *tableView = (UITableView*)self.view;
  2464. CGPoint touchPoint = [recognizer locationInView:self.view];
  2465. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2466. if ([self indexPathIsValid:indexPath])
  2467. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2468. else
  2469. _metadata = nil;
  2470. [self becomeFirstResponder];
  2471. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2472. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2473. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2474. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2475. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2476. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2477. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2478. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2479. [menuController setMenuVisible:YES animated:YES];
  2480. }
  2481. }
  2482. - (BOOL)canBecomeFirstResponder
  2483. {
  2484. return YES;
  2485. }
  2486. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2487. {
  2488. // For copy file, copy files, Open in ... :
  2489. //
  2490. // NO Directory
  2491. // NO Error Passcode
  2492. // NO In Session mode (download/upload)
  2493. // NO Template
  2494. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2495. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2496. else return NO;
  2497. }
  2498. if (@selector(copyFiles:) == action) {
  2499. if (_isSelectedMode) {
  2500. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2501. for (tableMetadata *metadata in selectedMetadatas) {
  2502. if (!metadata.directory && metadata.session.length == 0)
  2503. return YES;
  2504. }
  2505. }
  2506. return NO;
  2507. }
  2508. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2509. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2510. NSArray *items = [pasteboard items];
  2511. if ([items count] == 1) {
  2512. // Value : (NSData) fileID
  2513. NSDictionary *dic = [items objectAtIndex:0];
  2514. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2515. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2516. if (fileID) {
  2517. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2518. if (metadata) {
  2519. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2520. if (account) {
  2521. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2522. if (directoryUser)
  2523. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2524. return YES;
  2525. }
  2526. }
  2527. }
  2528. }
  2529. return NO;
  2530. }
  2531. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2532. BOOL isValid = NO;
  2533. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2534. NSArray *items = [pasteboard items];
  2535. if ([items count] <= 1) return NO;
  2536. for (NSDictionary *dic in items) {
  2537. // Value : (NSData) fileID
  2538. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2539. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2540. if (fileID) {
  2541. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2542. if (metadata) {
  2543. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2544. if (account) {
  2545. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2546. if (directoryUser) {
  2547. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2548. isValid = YES;
  2549. } else {
  2550. isValid = NO;
  2551. break;
  2552. }
  2553. } else {
  2554. isValid = NO;
  2555. break;
  2556. }
  2557. } else {
  2558. isValid = NO;
  2559. break;
  2560. }
  2561. } else {
  2562. isValid = NO;
  2563. break;
  2564. }
  2565. } else {
  2566. isValid = NO;
  2567. break;
  2568. }
  2569. }
  2570. return isValid;
  2571. }
  2572. return NO;
  2573. }
  2574. /************************************ COPY ************************************/
  2575. - (void)copyFile:(id)sender
  2576. {
  2577. // Remove all item
  2578. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2579. pasteboard.items = [[NSArray alloc] init];
  2580. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2581. [self copyFileToPasteboard:_metadata];
  2582. } else {
  2583. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2584. if (serverUrl)
  2585. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2586. }
  2587. }
  2588. - (void)copyFiles:(id)sender
  2589. {
  2590. // Remove all item
  2591. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2592. pasteboard.items = [[NSArray alloc] init];
  2593. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2594. for (tableMetadata *metadata in selectedMetadatas) {
  2595. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2596. [self copyFileToPasteboard:metadata];
  2597. } else {
  2598. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2599. if (serverUrl)
  2600. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2601. }
  2602. }
  2603. [self tableViewSelect:NO];
  2604. }
  2605. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2606. {
  2607. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2608. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2609. // Value : (NSData) fileID
  2610. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2611. [items addObject:item];
  2612. [pasteboard setItems:items];
  2613. }
  2614. /************************************ OPEN IN ... ******************************/
  2615. - (void)openinFile:(id)sender
  2616. {
  2617. [self openIn:_metadata];
  2618. }
  2619. /************************************ PASTE ************************************/
  2620. - (void)pasteFile:(id)sender
  2621. {
  2622. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2623. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2624. }
  2625. - (void)pasteFileEncrypted:(id)sender
  2626. {
  2627. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2628. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2629. }
  2630. - (void)pasteFiles:(id)sender
  2631. {
  2632. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2633. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2634. }
  2635. - (void)pasteFilesEncrypted:(id)sender
  2636. {
  2637. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2638. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2639. }
  2640. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2641. {
  2642. float timer = 0;
  2643. for (NSDictionary *dic in items) {
  2644. // Value : (NSData) fileID
  2645. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2646. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2647. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2648. if (metadata) {
  2649. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2650. if (account) {
  2651. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2652. if (directoryUser) {
  2653. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2654. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]];
  2655. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2656. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2657. });
  2658. timer += 0.1;
  2659. }
  2660. }
  2661. }
  2662. }
  2663. }
  2664. }
  2665. #pragma --------------------------------------------------------------------------------------------
  2666. #pragma mark ===== Lock Passcode =====
  2667. #pragma --------------------------------------------------------------------------------------------
  2668. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2669. {
  2670. return _failedAttempts;
  2671. }
  2672. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2673. {
  2674. return _lockUntilDate;
  2675. }
  2676. - (void)passcodeViewCloseButtonPressed:(id)sender
  2677. {
  2678. [self dismissViewControllerAnimated:YES completion:nil];
  2679. }
  2680. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2681. {
  2682. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2683. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2684. _lockUntilDate = nil;
  2685. _failedAttempts = 0;
  2686. aResultHandler(YES);
  2687. } else aResultHandler(NO);
  2688. } else aResultHandler(YES);
  2689. }
  2690. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2691. {
  2692. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2693. switch (aViewController.type) {
  2694. case BKPasscodeViewControllerCheckPasscodeType: {
  2695. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2696. // possiamo procedere alla prossima directory
  2697. [self performSegueDirectoryWithControlPasscode:false];
  2698. // avviamo la sessione Passcode Lock con now
  2699. app.sessionePasscodeLock = [NSDate date];
  2700. }
  2701. // disattivazione lock cartella
  2702. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2703. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2704. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2705. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2706. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2707. }
  2708. [self tableViewReloadData];
  2709. }
  2710. }
  2711. break;
  2712. default:
  2713. break;
  2714. }
  2715. }
  2716. - (void)comandoLockPassword
  2717. {
  2718. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2719. if (!serverUrl) return;
  2720. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2721. // se non è abilitato il Lock Passcode esci
  2722. if ([[CCUtility getBlockCode] length] == 0) {
  2723. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2724. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2725. [alertController addAction:okAction];
  2726. [self presentViewController:alertController animated:YES completion:nil];
  2727. return;
  2728. }
  2729. // se è richiesta la disattivazione si chiede la password
  2730. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2731. if (directory.lock) {
  2732. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2733. viewController.delegate = self;
  2734. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2735. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2736. viewController.inputViewTitlePassword = YES;
  2737. if ([CCUtility getSimplyBlockCode]) {
  2738. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2739. viewController.passcodeInputView.maximumLength = 6;
  2740. } else {
  2741. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2742. viewController.passcodeInputView.maximumLength = 64;
  2743. }
  2744. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2745. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2746. viewController.touchIDManager = touchIDManager;
  2747. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2748. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2749. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2750. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2751. [self presentViewController:navigationController animated:YES completion:nil];
  2752. return;
  2753. }
  2754. // ---------------- ACTIVATE PASSWORD
  2755. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2756. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2757. if ([self indexPathIsValid:indexPath])
  2758. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2759. } else {
  2760. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2761. }
  2762. }
  2763. #pragma mark -
  2764. #pragma --------------------------------------------------------------------------------------------
  2765. #pragma mark ===== Swipe Tablet -> menu =====
  2766. #pragma --------------------------------------------------------------------------------------------
  2767. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2768. {
  2769. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2770. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2771. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2772. return NO;
  2773. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2774. return NO;
  2775. else
  2776. return YES;
  2777. }
  2778. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2779. {
  2780. }
  2781. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2782. {
  2783. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2784. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2785. if (direction == MGSwipeDirectionRightToLeft) {
  2786. // Delete
  2787. if (index == 0)
  2788. [self swipeDelete:indexPath];
  2789. // More
  2790. if (index == 1)
  2791. [self swipeMore:indexPath];
  2792. }
  2793. if (direction == MGSwipeDirectionLeftToRight) {
  2794. if (_metadata.favorite)
  2795. [self removeFavorite:_metadata];
  2796. else
  2797. [self addFavorite:_metadata];
  2798. }
  2799. return YES;
  2800. }
  2801. - (void)swipeDelete:(NSIndexPath *)indexPath
  2802. {
  2803. // Directory locked ?
  2804. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2805. if (!lockServerUrl) return;
  2806. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2807. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  2808. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2809. return;
  2810. }
  2811. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2812. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2813. [self performSelector:@selector(deleteFile) withObject:nil];
  2814. }]];
  2815. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2816. [alertController dismissViewControllerAnimated:YES completion:nil];
  2817. }]];
  2818. alertController.popoverPresentationController.sourceView = self.view;
  2819. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2820. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2821. [alertController.view layoutIfNeeded];
  2822. [self presentViewController:alertController animated:YES completion:nil];
  2823. }
  2824. - (void)swipeMore:(NSIndexPath *)indexPath
  2825. {
  2826. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2827. if (!serverUrl) return;
  2828. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  2829. titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2830. if (_metadata.favorite) {
  2831. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2832. } else {
  2833. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2834. }
  2835. if (_metadata.directory) {
  2836. // calcolo lockServerUrl
  2837. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2838. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2839. if (directory.lock)
  2840. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2841. else
  2842. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2843. }
  2844. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2845. // ******************************************* AHKActionSheet *******************************************
  2846. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2847. actionSheet.animationDuration = 0.2;
  2848. actionSheet.buttonHeight = 50.0;
  2849. actionSheet.cancelButtonHeight = 50.0f;
  2850. actionSheet.separatorHeight = 5.0f;
  2851. actionSheet.automaticallyTintButtonImages = @(NO);
  2852. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  2853. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2854. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2855. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2856. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2857. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2858. // ******************************************* DIRECTORY *******************************************
  2859. if (_metadata.directory) {
  2860. BOOL lockDirectory = NO;
  2861. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2862. // Directory bloccata ?
  2863. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  2864. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  2865. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2866. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2867. [actionSheet addButtonWithTitle: _metadata.fileName
  2868. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  2869. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2870. height: 50.0
  2871. type: AHKActionSheetButtonTypeDisabled
  2872. handler: nil
  2873. ];
  2874. if (!lockDirectory) {
  2875. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2876. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  2877. backgroundColor:[UIColor whiteColor]
  2878. height: 50.0
  2879. type:AHKActionSheetButtonTypeDefault
  2880. handler:^(AHKActionSheet *as) {
  2881. [self openWindowShare:_metadata];
  2882. }];
  2883. }
  2884. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2885. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2886. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2887. backgroundColor:[UIColor whiteColor]
  2888. height: 50.0
  2889. type:AHKActionSheetButtonTypeDefault
  2890. handler:^(AHKActionSheet *as) {
  2891. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2892. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2893. textField.text = _metadata.fileName;
  2894. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2895. //textField.delegate = self;
  2896. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2897. }];
  2898. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2899. NSLog(@"Cancel action");
  2900. }];
  2901. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2902. UITextField *fileName = alertController.textFields.firstObject;
  2903. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2904. }];
  2905. okAction.enabled = NO;
  2906. [alertController addAction:cancelAction];
  2907. [alertController addAction:okAction];
  2908. [self presentViewController:alertController animated:YES completion:nil];
  2909. }];
  2910. }
  2911. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2912. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2913. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  2914. backgroundColor:[UIColor whiteColor]
  2915. height: 50.0
  2916. type:AHKActionSheetButtonTypeDefault
  2917. handler:^(AHKActionSheet *as) {
  2918. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2919. }];
  2920. }
  2921. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2922. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2923. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  2924. backgroundColor:[UIColor whiteColor]
  2925. height: 50.0
  2926. type:AHKActionSheetButtonTypeDefault
  2927. handler:^(AHKActionSheet *as) {
  2928. // Settings new folder Automatatic upload
  2929. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2930. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2931. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  2932. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  2933. if (app.activeAccount.length > 0 && app.activePhotos)
  2934. [app.activePhotos reloadDatasourceForced];
  2935. [self readFolder:serverUrl];
  2936. NSLog(@"[LOG] Update Folder Photo");
  2937. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  2938. if ([autoUploadPath length] > 0) {
  2939. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  2940. }
  2941. }];
  2942. }
  2943. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2944. [actionSheet addButtonWithTitle:titoloLock
  2945. image:[UIImage imageNamed:@"actionSheetLock"]
  2946. backgroundColor:[UIColor whiteColor]
  2947. height: 50.0
  2948. type:AHKActionSheetButtonTypeEncrypted
  2949. handler:^(AHKActionSheet *as) {
  2950. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2951. }];
  2952. }
  2953. /*
  2954. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  2955. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  2956. image:[UIImage imageNamed:@"actionSheetCrypto"]
  2957. backgroundColor:[UIColor whiteColor]
  2958. height: 50.0
  2959. type:AHKActionSheetButtonTypeEncrypted
  2960. handler:^(AHKActionSheet *as) {
  2961. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  2962. }];
  2963. }
  2964. */
  2965. [actionSheet show];
  2966. }
  2967. // ******************************************* FILE *******************************************
  2968. if (!_metadata.directory) {
  2969. UIImage *iconHeader;
  2970. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2971. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  2972. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  2973. else
  2974. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2975. [actionSheet addButtonWithTitle: _metadata.fileName
  2976. image: iconHeader
  2977. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2978. height: 50.0
  2979. type: AHKActionSheetButtonTypeDisabled
  2980. handler: nil
  2981. ];
  2982. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2983. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brand]
  2984. backgroundColor:[UIColor whiteColor]
  2985. height: 50.0
  2986. type:AHKActionSheetButtonTypeDefault
  2987. handler:^(AHKActionSheet *as) {
  2988. [self openWindowShare:_metadata];
  2989. }];
  2990. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2991. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  2992. backgroundColor:[UIColor whiteColor]
  2993. height: 50.0
  2994. type:AHKActionSheetButtonTypeDefault
  2995. handler:^(AHKActionSheet *as) {
  2996. [self performSelector:@selector(openIn:) withObject:_metadata];
  2997. }];
  2998. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2999. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3000. backgroundColor:[UIColor whiteColor]
  3001. height: 50.0
  3002. type:AHKActionSheetButtonTypeDefault
  3003. handler:^(AHKActionSheet *as) {
  3004. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3005. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3006. textField.text = _metadata.fileName;
  3007. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3008. }];
  3009. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3010. NSLog(@"Cancel action");
  3011. }];
  3012. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3013. UITextField *fileName = alertController.textFields.firstObject;
  3014. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3015. }];
  3016. okAction.enabled = NO;
  3017. [alertController addAction:cancelAction];
  3018. [alertController addAction:okAction];
  3019. [self presentViewController:alertController animated:YES completion:nil];
  3020. }];
  3021. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3022. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3023. backgroundColor:[UIColor whiteColor]
  3024. height: 50.0
  3025. type:AHKActionSheetButtonTypeDefault
  3026. handler:^(AHKActionSheet *as) {
  3027. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3028. }];
  3029. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3030. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3031. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3032. backgroundColor:[UIColor whiteColor]
  3033. height: 50.0
  3034. type:AHKActionSheetButtonTypeDefault
  3035. handler:^(AHKActionSheet *as) {
  3036. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3037. }];
  3038. }
  3039. /*
  3040. if (app.isCryptoCloudMode) {
  3041. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3042. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3043. backgroundColor:[UIColor whiteColor]
  3044. height: 50.0
  3045. type:AHKActionSheetButtonTypeEncrypted
  3046. handler:^(AHKActionSheet *as) {
  3047. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3048. }];
  3049. }
  3050. */
  3051. #ifdef DEBUG
  3052. /*
  3053. [actionSheet addButtonWithTitle:@"Hide file"
  3054. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"admin"] color:[NCBrandColor sharedInstance].brand]
  3055. backgroundColor:[UIColor whiteColor]
  3056. height: 50.0
  3057. type:AHKActionSheetButtonTypeDefault
  3058. handler:^(AHKActionSheet *as) {
  3059. [[NCManageDatabase sharedInstance] setMetadataStatusWithFileID:_metadata.fileID status:k_metadataStatusHide];
  3060. [self reloadDatasource];
  3061. }];
  3062. */
  3063. #endif
  3064. [actionSheet show];
  3065. }
  3066. }
  3067. #pragma --------------------------------------------------------------------------------------------
  3068. #pragma mark - ==== Datasource ====
  3069. #pragma --------------------------------------------------------------------------------------------
  3070. - (void)clearDateReadDataSource:(NSNotification *)notification
  3071. {
  3072. _dateReadDataSource = Nil;
  3073. [self reloadDatasource];
  3074. }
  3075. - (void)reloadDatasource
  3076. {
  3077. [self reloadDatasource:_serverUrl];
  3078. }
  3079. - (void)reloadDatasource:(NSString *)serverUrl
  3080. {
  3081. // test
  3082. if (app.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3083. return;
  3084. // Search Mode
  3085. if(_isSearchMode) {
  3086. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3087. [self tableViewReloadData];
  3088. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3089. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3090. _noFilesSearchDescription = @"";
  3091. }
  3092. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3093. _noFilesSearchTitle = @"";
  3094. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3095. }
  3096. [self.tableView reloadEmptyDataSet];
  3097. return;
  3098. }
  3099. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3100. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3101. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3102. if (main) {
  3103. [main reloadDatasource];
  3104. } else {
  3105. [self tableViewReloadData];
  3106. [app.activeTransfers reloadDatasource];
  3107. }
  3108. return;
  3109. }
  3110. [app.activeTransfers reloadDatasource];
  3111. // Settaggio variabili per le ottimizzazioni
  3112. _directoryGroupBy = [CCUtility getGroupBySettings];
  3113. _directoryOrder = [CCUtility getOrderSettings];
  3114. // Controllo data lettura Data Source
  3115. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3116. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3117. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3118. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3119. _dateReadDataSource = [NSDate date];
  3120. // Data Source
  3121. NSString *sorted = _directoryOrder;
  3122. if ([sorted isEqualToString:@"fileName"])
  3123. sorted = @"fileName";
  3124. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3125. if (directoryID) {
  3126. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3127. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3128. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3129. }
  3130. } else {
  3131. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3132. }
  3133. [self tableViewReloadData];
  3134. }
  3135. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3136. {
  3137. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3138. if (selectedRows.count > 0) {
  3139. for (NSIndexPath *selectionIndex in selectedRows) {
  3140. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3141. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3142. [metadatas addObject:metadata];
  3143. }
  3144. }
  3145. return metadatas;
  3146. }
  3147. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3148. {
  3149. NSInteger section = indexPath.section + 1;
  3150. NSInteger row = indexPath.row + 1;
  3151. NSInteger totSections = [_sectionDataSource.sections count] ;
  3152. if ((totSections < section) || (section > totSections)) {
  3153. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3154. return nil;
  3155. }
  3156. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3157. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3158. if (fileIDs) {
  3159. NSInteger totRows =[fileIDs count] ;
  3160. if ((totRows < row) || (row > totRows)) {
  3161. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3162. return nil;
  3163. }
  3164. } else {
  3165. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3166. return nil;
  3167. }
  3168. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3169. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3170. return metadata;
  3171. }
  3172. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3173. {
  3174. NSInteger totSections =[_sectionDataSource.sections count] ;
  3175. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3176. return nil;
  3177. }
  3178. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3179. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3180. }
  3181. #pragma --------------------------------------------------------------------------------------------
  3182. #pragma mark - ==== Table ====
  3183. #pragma --------------------------------------------------------------------------------------------
  3184. - (void)tableViewSelect:(BOOL)edit
  3185. {
  3186. // chiudiamo eventuali swipe aperti
  3187. if (edit)
  3188. [self.tableView setEditing:NO animated:NO];
  3189. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3190. [self.tableView setEditing:edit animated:YES];
  3191. _isSelectedMode = edit;
  3192. if (edit)
  3193. [self setUINavigationBarSelected];
  3194. else
  3195. [self setUINavigationBarDefault];
  3196. [_selectedFileIDsMetadatas removeAllObjects];
  3197. [self setTitle];
  3198. }
  3199. - (void)tableViewReloadData
  3200. {
  3201. // store selected cells before relod
  3202. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3203. //store swipeOffset before relod
  3204. [_statusSwipeCell removeAllObjects];
  3205. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3206. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3207. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3208. }
  3209. // reload table view
  3210. [self.tableView reloadData];
  3211. // selected cells stored
  3212. for (NSIndexPath *path in indexPaths)
  3213. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3214. [self setTableViewFooter];
  3215. if (self.tableView.editing)
  3216. [self setTitle];
  3217. }
  3218. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3219. {
  3220. if (tableView.editing == 1) {
  3221. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3222. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3223. return NO;
  3224. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3225. return NO;
  3226. else
  3227. return YES;
  3228. } else {
  3229. [_selectedFileIDsMetadatas removeAllObjects];
  3230. }
  3231. return YES;
  3232. }
  3233. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3234. {
  3235. return 60;
  3236. }
  3237. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3238. {
  3239. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3240. }
  3241. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3242. {
  3243. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3244. }
  3245. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3246. {
  3247. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3248. NSString *sectionTitle = [sections objectAtIndex:section];
  3249. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3250. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3251. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3252. return 20.f;
  3253. }
  3254. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3255. {
  3256. float shift;
  3257. UIVisualEffectView *visualEffectView;
  3258. NSString *titleSection;
  3259. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3260. return nil;
  3261. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3262. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3263. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3264. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3265. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3266. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3267. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3268. else titleSection = NSLocalizedString(titleSection,nil);
  3269. // Format title
  3270. NSString *currentDevice = [CCUtility currentDevice];
  3271. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3272. visualEffectView = [[UIVisualEffectView alloc] init];
  3273. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3274. } else {
  3275. UIVisualEffect *blurEffect;
  3276. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3277. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3278. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3279. }
  3280. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3281. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3282. shift = - 35;
  3283. else
  3284. shift = - 20;
  3285. } else shift = - 10;
  3286. // Title
  3287. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3288. titleLabel.backgroundColor = [UIColor clearColor];
  3289. titleLabel.textColor = [UIColor blackColor];
  3290. titleLabel.font = [UIFont systemFontOfSize:12];
  3291. titleLabel.textAlignment = NSTextAlignmentLeft;
  3292. titleLabel.text = titleSection;
  3293. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3294. [visualEffectView.contentView addSubview:titleLabel];
  3295. // Elements
  3296. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3297. elementLabel.backgroundColor = [UIColor clearColor];
  3298. elementLabel.textColor = [UIColor blackColor];;
  3299. elementLabel.font = [UIFont systemFontOfSize:12];
  3300. elementLabel.textAlignment = NSTextAlignmentRight;
  3301. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3302. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3303. NSUInteger rowsCount = [metadatas count];
  3304. if (rowsCount == 0) return nil;
  3305. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3306. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3307. [visualEffectView.contentView addSubview:elementLabel];
  3308. return visualEffectView;
  3309. }
  3310. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3311. {
  3312. return [_sectionDataSource.sections indexOfObject:title];
  3313. }
  3314. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3315. {
  3316. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3317. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3318. else
  3319. return nil;
  3320. }
  3321. /*
  3322. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3323. {
  3324. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3325. }
  3326. }
  3327. */
  3328. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3329. {
  3330. NSString *typeCell;
  3331. NSString *dataFile;
  3332. NSString *lunghezzaFile;
  3333. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3334. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3335. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3336. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3337. if (!serverUrl)
  3338. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3339. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3340. else typeCell = @"CellMainTransfer";
  3341. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3342. // variable base
  3343. cell.delegate = self;
  3344. cell.indexPath = indexPath;
  3345. // separator
  3346. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3347. // change color selection
  3348. UIView *selectionColor = [[UIView alloc] init];
  3349. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3350. cell.selectedBackgroundView = selectionColor;
  3351. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3352. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3353. // ----------------------------------------------------------------------------------------------------------
  3354. // DEFAULT
  3355. // ----------------------------------------------------------------------------------------------------------
  3356. cell.file.image = nil;
  3357. cell.status.image = nil;
  3358. cell.favorite.image = nil;
  3359. cell.shared.image = nil;
  3360. cell.local.image = nil;
  3361. cell.labelTitle.enabled = YES;
  3362. cell.labelTitle.text = @"";
  3363. cell.labelInfoFile.enabled = YES;
  3364. cell.labelInfoFile.text = @"";
  3365. cell.progressView.progress = 0.0;
  3366. cell.progressView.hidden = YES;
  3367. cell.cancelTaskButton.hidden = YES;
  3368. cell.reloadTaskButton.hidden = YES;
  3369. cell.stopTaskButton.hidden = YES;
  3370. cell.labelTitle.textColor = [UIColor blackColor];
  3371. // ----------------------------------------------------------------------------------------------------------
  3372. // File Name & Folder
  3373. // ----------------------------------------------------------------------------------------------------------
  3374. // nome del file
  3375. cell.labelTitle.text = metadata.fileName;
  3376. // è una directory
  3377. if (metadata.directory) {
  3378. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3379. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3380. lunghezzaFile = @" ";
  3381. // ----------------------------------------------------------------------------------------------------------
  3382. // Favorite Folder
  3383. // ----------------------------------------------------------------------------------------------------------
  3384. if (metadata.favorite) {
  3385. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3386. }
  3387. } else {
  3388. // File
  3389. dataFile = [CCUtility dateDiff:metadata.date];
  3390. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3391. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3392. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3393. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3394. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3395. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3396. cell.local.image = [UIImage imageNamed:@"local"];
  3397. else
  3398. cell.local.image = nil;
  3399. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3400. cell.accessoryType = UITableViewCellAccessoryNone;
  3401. }
  3402. // ----------------------------------------------------------------------------------------------------------
  3403. // File Image View
  3404. // ----------------------------------------------------------------------------------------------------------
  3405. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3406. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3407. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3408. } else {
  3409. if (metadata.directory)
  3410. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3411. else
  3412. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3413. if (metadata.thumbnailExists)
  3414. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3415. }
  3416. // ----------------------------------------------------------------------------------------------------------
  3417. // Image Status cyptated & Lock Passcode
  3418. // ----------------------------------------------------------------------------------------------------------
  3419. // Directory con passcode lock attivato
  3420. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3421. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3422. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3423. cell.status.image = [UIImage imageNamed:@"passcode"];
  3424. // ----------------------------------------------------------------------------------------------------------
  3425. // Favorite
  3426. // ----------------------------------------------------------------------------------------------------------
  3427. if (metadata.favorite) {
  3428. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3429. }
  3430. // ----------------------------------------------------------------------------------------------------------
  3431. // Share
  3432. // ----------------------------------------------------------------------------------------------------------
  3433. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3434. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3435. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3436. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3437. // Aggiungiamo il Tap per le shared
  3438. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3439. // Shared with you
  3440. if (isShare) {
  3441. if (metadata.directory) {
  3442. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3443. cell.accessoryType = UITableViewCellAccessoryNone;
  3444. }
  3445. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3446. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3447. [tap setNumberOfTapsRequired:1];
  3448. cell.shared.userInteractionEnabled = YES;
  3449. [cell.shared addGestureRecognizer:tap];
  3450. }
  3451. // Mounted with you
  3452. if (isMounted) {
  3453. if (metadata.directory) {
  3454. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3455. cell.accessoryType = UITableViewCellAccessoryNone;
  3456. }
  3457. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3458. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3459. [tap setNumberOfTapsRequired:1];
  3460. cell.shared.userInteractionEnabled = YES;
  3461. [cell.shared addGestureRecognizer:tap];
  3462. }
  3463. // You share
  3464. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3465. if (metadata.directory) {
  3466. if ([shareLink length] > 0)
  3467. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3468. if ([shareUserAndGroup length] > 0)
  3469. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3470. cell.shared.userInteractionEnabled = NO;
  3471. } else {
  3472. if ([shareLink length] > 0)
  3473. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3474. if ([shareUserAndGroup length] > 0)
  3475. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3476. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3477. [tap setNumberOfTapsRequired:1];
  3478. cell.shared.userInteractionEnabled = YES;
  3479. [cell.shared addGestureRecognizer:tap];
  3480. }
  3481. }
  3482. } else {
  3483. cell.shared.userInteractionEnabled = NO;
  3484. }
  3485. // ----------------------------------------------------------------------------------------------------------
  3486. // downloadFile
  3487. // ----------------------------------------------------------------------------------------------------------
  3488. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3489. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3490. // sessionTaskIdentifier : RELOAD + STOP
  3491. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3492. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3493. cell.cancelTaskButton.hidden = NO;
  3494. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3495. cell.reloadTaskButton.hidden = NO;
  3496. }
  3497. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3498. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3499. if (progress > 0) {
  3500. cell.progressView.progressTintColor = [UIColor blackColor];
  3501. cell.progressView.progress = progress;
  3502. cell.progressView.hidden = NO;
  3503. }
  3504. // ----------------------------------------------------------------------------------------------------------
  3505. // downloadFile Error
  3506. // ----------------------------------------------------------------------------------------------------------
  3507. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3508. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3509. if ([metadata.sessionError length] == 0)
  3510. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3511. else
  3512. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3513. }
  3514. }
  3515. // ----------------------------------------------------------------------------------------------------------
  3516. // uploadFile
  3517. // ----------------------------------------------------------------------------------------------------------
  3518. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3519. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3520. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3521. cell.cancelTaskButton.hidden = NO;
  3522. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3523. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3524. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3525. cell.reloadTaskButton.hidden = NO;
  3526. cell.stopTaskButton.hidden = YES;
  3527. } else {
  3528. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3529. cell.stopTaskButton.hidden = NO;
  3530. cell.reloadTaskButton.hidden = YES;
  3531. }
  3532. // se non c'è una preview in bianconero metti l'immagine di default
  3533. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3534. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3535. cell.labelTitle.enabled = NO;
  3536. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3537. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3538. if (progress > 0) {
  3539. cell.progressView.progressTintColor = [UIColor blackColor];
  3540. cell.progressView.progress = progress;
  3541. cell.progressView.hidden = NO;
  3542. }
  3543. // ----------------------------------------------------------------------------------------------------------
  3544. // uploadFileError
  3545. // ----------------------------------------------------------------------------------------------------------
  3546. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3547. cell.labelTitle.enabled = NO;
  3548. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3549. if ([metadata.sessionError length] == 0)
  3550. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3551. else
  3552. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3553. }
  3554. }
  3555. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3556. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3557. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3558. // ======== MGSwipe ========
  3559. if (metadata.favorite)
  3560. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3561. else
  3562. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3563. cell.leftExpansion.buttonIndex = 0;
  3564. cell.leftExpansion.fillOnTrigger = NO;
  3565. //centerIconOverText
  3566. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3567. [favoriteButton centerIconOverText];
  3568. //Right
  3569. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3570. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3571. //centerIconOverText
  3572. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3573. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3574. [deleteButton centerIconOverText];
  3575. [moreButton centerIconOverText];
  3576. //restore swipeOffset after relod
  3577. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3578. if (swipeOffset < 0) {
  3579. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3580. [_statusSwipeCell removeObjectForKey:indexPath];
  3581. } else if (swipeOffset > 0) {
  3582. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3583. [_statusSwipeCell removeObjectForKey:indexPath];
  3584. }
  3585. return cell;
  3586. }
  3587. - (void)setTableViewFooter
  3588. {
  3589. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3590. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3591. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3592. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3593. UIFont *appFont = [UIFont systemFontOfSize:12];
  3594. footerLabel.font = appFont;
  3595. footerLabel.textColor = [UIColor grayColor];
  3596. footerLabel.backgroundColor = [UIColor clearColor];
  3597. footerLabel.textAlignment = NSTextAlignmentCenter;
  3598. NSString *folders;
  3599. NSString *files;
  3600. NSString *footerText;
  3601. if (_sectionDataSource.directories > 1) {
  3602. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3603. } else if (_sectionDataSource.directories == 1){
  3604. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3605. } else {
  3606. folders = @"";
  3607. }
  3608. if (_sectionDataSource.files > 1) {
  3609. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3610. } else if (_sectionDataSource.files == 1){
  3611. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3612. } else {
  3613. files = @"";
  3614. }
  3615. if ([folders isEqualToString:@""]) {
  3616. footerText = files;
  3617. } else if ([files isEqualToString:@""]) {
  3618. footerText = folders;
  3619. } else {
  3620. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3621. }
  3622. footerLabel.text = footerText;
  3623. [footerView addSubview:footerLabel];
  3624. [self.tableView setTableFooterView:footerView];
  3625. }
  3626. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3627. {
  3628. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3629. // settiamo il record file.
  3630. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3631. if (!_metadata)
  3632. return;
  3633. // se non può essere selezionata deseleziona
  3634. if ([cell isEditing] == NO)
  3635. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3636. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3637. if (self.tableView.editing) {
  3638. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3639. [self setTitle];
  3640. return;
  3641. }
  3642. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3643. if (!serverUrl) return;
  3644. // se è in corso una sessione
  3645. if ([_metadata.session length] > 0) return;
  3646. // file
  3647. if (_metadata.directory == NO) {
  3648. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3649. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3650. #ifdef DEBUG
  3651. // TEST ENCRYPTED
  3652. if ([_metadata.fileName containsString:@".dms"]) {
  3653. [[NCClientEncryption sharedManager] decryptMetadata:_metadata activeUrl:app.directoryUser];
  3654. }
  3655. #endif
  3656. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3657. } else {
  3658. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3659. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3660. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3661. }
  3662. }
  3663. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3664. }
  3665. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3666. {
  3667. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3668. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3669. [self setTitle];
  3670. }
  3671. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3672. {
  3673. if (!indexPath)
  3674. return NO;
  3675. NSInteger section = indexPath.section;
  3676. NSInteger row = indexPath.row;
  3677. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3678. if (section > lastSectionIndex || lastSectionIndex < 0)
  3679. return NO;
  3680. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3681. if (rowCount < 0)
  3682. return NO;
  3683. return row <= rowCount;
  3684. }
  3685. #pragma --------------------------------------------------------------------------------------------
  3686. #pragma mark ===== Navigation ====
  3687. #pragma --------------------------------------------------------------------------------------------
  3688. - (BOOL)shouldPerformSegue
  3689. {
  3690. // if background return
  3691. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3692. if (self.view.window == NO)
  3693. return NO;
  3694. // Collapsed ma siamo già in detail esci
  3695. if (self.splitViewController.isCollapsed)
  3696. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3697. return YES;
  3698. }
  3699. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3700. {
  3701. id viewController = segue.destinationViewController;
  3702. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3703. tableMetadata *metadata;
  3704. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3705. UINavigationController *nav = viewController;
  3706. _detailViewController = (CCDetail *)nav.topViewController;
  3707. } else {
  3708. _detailViewController = segue.destinationViewController;
  3709. }
  3710. if ([sender isKindOfClass:[tableMetadata class]]) {
  3711. metadata = sender;
  3712. [allRecordsDataSourceImagesVideos addObject:sender];
  3713. } else {
  3714. metadata = _metadata;
  3715. for (NSString *fileID in _sectionDataSource.allEtag) {
  3716. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3717. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3718. [allRecordsDataSourceImagesVideos addObject:metadata];
  3719. }
  3720. }
  3721. _detailViewController.metadataDetail = metadata;
  3722. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3723. _detailViewController.dateFilterQuery = nil;
  3724. [_detailViewController setTitle:metadata.fileName];
  3725. }
  3726. // can i go to next viewcontroller
  3727. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3728. {
  3729. NSString *nomeDir;
  3730. if(self.tableView.editing == NO) {
  3731. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3732. if (!serverUrl) return;
  3733. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3734. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3735. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3736. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  3737. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3738. viewController.delegate = self;
  3739. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3740. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3741. viewController.inputViewTitlePassword = YES;
  3742. if ([CCUtility getSimplyBlockCode]) {
  3743. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3744. viewController.passcodeInputView.maximumLength = 6;
  3745. } else {
  3746. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3747. viewController.passcodeInputView.maximumLength = 64;
  3748. }
  3749. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3750. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3751. viewController.touchIDManager = touchIDManager;
  3752. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3753. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3754. //viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3755. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3756. [self presentViewController:navController animated:YES completion:nil];
  3757. return;
  3758. }
  3759. nomeDir = _metadata.fileName;
  3760. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3761. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  3762. if (!viewController) {
  3763. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3764. viewController.serverUrl = serverUrlPush;
  3765. viewController.titleMain = _metadata.fileName;
  3766. viewController.textBackButton = _titleMain;
  3767. // save self
  3768. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  3769. [self.navigationController pushViewController:viewController animated:YES];
  3770. } else {
  3771. if (viewController.isViewLoaded) {
  3772. // Fix : Application tried to present modally an active controller
  3773. if ([self.navigationController isBeingPresented]) {
  3774. // being presented
  3775. } else if ([self.navigationController isMovingToParentViewController]) {
  3776. // being pushed
  3777. } else {
  3778. [self.navigationController pushViewController:viewController animated:YES];
  3779. }
  3780. }
  3781. }
  3782. }
  3783. }
  3784. @end