CCMain.m 221 KB

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